Home > Software design >  I want to change scene when the counter reaches 0 but it does not work
I want to change scene when the counter reaches 0 but it does not work

Time:05-24

public class EnemyCounter : MonoBehaviour
{
    GameObject[] enemies;

    public Text enemyCountText;

    void Start()
    {
    }

    void Update()
    {
        enemies = GameObject.FindGameObjectsWithTag("bad");

        enemyCountText.text = "Enemies : "  
                              enemies.Length.ToString();

        if (enemies == null)
        {
            SceneManager.LoadScene("Level2");
        }
    }
}

CodePudding user response:

Empty arrays are not the same as null arrays. An array that has never been defined, GameObject[] enemies;, would be null. However, if this array is created as new and filled with values it is no longer null, even after removing those values.

Arrays are pointers to data stored in memory. Removing the data stored in memory does not remove the pointer.

My recommendation is to also check the length:

if (enemies == null || enemies.Length == 0) 

CodePudding user response:

This code does not work when you have defined a list. In fact, a list with zero members is not equal to null. null means no list definition.

enemies == null;

Change the code this way:

if (enemies.Length == 0)
{
    SceneManager.LoadScene("Level2");
}
  • Related