简体   繁体   中英

I want to change scene when the counter reaches 0 but it does not work

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"); } } }

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) 

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM