[英]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;
空 arrays 和 null 不一样 arrays 一个从来没有定义过的数组,GameObject 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. ,将是 null。但是,如果此数组是新创建的并填充了值,则它不再是 null,即使在删除这些值之后也是如此。
Arrays are pointers to data stored in memory. Removing the data stored in memory does not remove the pointer. Arrays 是指向 memory 中存储的数据的指针。删除 memory 中存储的数据不会删除指针。
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.事实上,零成员列表不等于 null。null 表示没有列表定义。
enemies == null;
Change the code this way:以这种方式更改代码:
if (enemies.Length == 0)
{
SceneManager.LoadScene("Level2");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.