简体   繁体   English

我想在计数器达到 0 时更改场景,但它不起作用

[英]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.

相关问题 Unity中的LoadScene()函数何时更改场景? - When does the LoadScene() function in Unity change the scene? 在Unity中,我想改变场景,然后改变显示的文字,但场景改变总是最后发生 - In Unity, I want to change the scene and then change the text displayed, but the scene change always happens last 更改场景时WebCamTexture崩溃 - WebCamTexture crashes when I change the scene 我想在“生命值”变为零但我的GameOver场景未打开并且生命值的倒计时继续时更改场景 - I want to change scenes when the Lives Value turns zero but my GameOver scene isn't opening and the countdown of the lives values continues 为什么我的玩家健康在我想要的时候没有改变 - Why does my player health not change when I want it to 我可以通过公共空间或其他方式更改场景(价值?)吗? 我不想每次都编写新代码并更改要加载的场景 - Can i change the scene (value?) via public void or something? I do not want to make a new code everytime and change the scene that is going to load 在场景Unity中未检测到输入。 从该场景开始游戏时有效; 否则不起作用 - Input not being detected in scene Unity. Works when starting the game from that scene; does not work otherwise 为什么计数器在线程池中不起作用 - Why the counter does not work in threadpool 加载我不想要的场景时Unity / C#播放Audioclip - Unity/C# plays Audioclip when loading scene which I dont want 我想像Minecraft一样在场景中保存对象 - I want to save objects on the scene like Minecraft
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM