你好,
我刚开始编码,所以请耐心等待。我有一个协同程序,我想打电话给它,所以我的重生有点延迟。然而,除了延迟,它什么都做。Unity C#:(
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
Destroy(gameObject);
StartCoroutine(Reset());
}
}
IEnumerator Reset()
{
yield return new WaitForSeconds(4);
LevelManager.instance.Respawn();
}
}
很简单,对象已经被销毁,所以下一帧Destroy(gameObject);
之后的内容(Script(不会起作用,正如我在评论中告诉你的那样,在IEnumerator
上设置一条日志消息来查看它。要了解它是如何工作的:请检查此脚本
void Awake() // the First Call // all lines inside Awake is Called
{
Destroy(gameObject); // Object is now Destroyed
print(1); // on the Same Frame Call // Printed
StartCoroutine(Reset()); // Called
}
IEnumerator Reset()
{
print(2); // will printed ... Called and on the same frame
yield return new WaitForSeconds(1); // Called but will be destroyed in the next frame
print(3); // not printed ..
}
private void Start() // Start will be called after the Awake calls are finished and the object still exists and is active so it will not be Called
{
print(4); // not printed ..
}
正如Mohamed所指出的,执行游戏对象在帧结束时正确触发WaitForSeconds之前就被破坏了,因此您的代码无法到达LevelManager.instance.Respawn((。如果像这样在Respawn((之后执行destroy,会干扰流的其余部分吗?
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
StartCoroutine(Reset());
}
}
IEnumerator Reset()
{
yield return new WaitForSeconds(4);
LevelManager.instance.Respawn();
Destroy(gameObject);
}
}