Home > OS >  Cant instiantiate null on unit test in unity
Cant instiantiate null on unit test in unity

Time:12-20

I try to run a test on my gameManager like that:

[UnityTest]
public IEnumerator CheckControllerOnPlayerMode()
{
    GameObject gameGameObject = MonoBehaviour.Instantiate(Resources.Load<GameObject>("Prefabs/GameManager"));
    GameManager gameManager = gameGameObject.GetComponent<GameManager>();
    yield return null;
    gameManager.StartGame(GameMode.Player);
    yield return new Update();
}

and this is my relevent code on my gameManager: private void InitControllers(GameMode mode) {

    if (player1 != null) Destroy(player1.gameObject);
    if (player2 != null) Destroy(player2.gameObject);

    if (mode == GameMode.Player)
    {
        GameObject localPlayerGO = Instantiate(localPlayer);
        GameObject secondLocalPlayerGO = Instantiate(localPlayer);
        player1 = localPlayerGO.GetComponent<Controller>();
        player2 = secondLocalPlayerGO.GetComponent<Controller>();
    }
    else if (mode == GameMode.PC)
    {
        GameObject localPlayerGO = Instantiate(localPlayer);
        GameObject pcPlayerGO = Instantiate(pcPlayer);
        player1 = localPlayerGO.GetComponent<Controller>();
        player2 = pcPlayerGO.GetComponent<Controller>();
    }
}

when localPlayer and pcPlayer are prefabs that I refer to the script, but my test get an error System.NullReferenceException : Object reference not set to an instance of an object on the Instantiate inside my gameManager, how do I fix it?

CodePudding user response:

The answer was to remove the Destroy from my code:

if (player1 != null) Destroy(player1.gameObject);
if (player2 != null) Destroy(player2.gameObject);

probably Destroy will actually destroy at the end of the frame.

  • Related