首页 > 解决方案 > 没有调用协程

问题描述

再会,

我是编码新手,所以请耐心等待。我有一个我想调用的协程,所以我的重生有延迟。但是,除了延迟之外,它什么都做。统一 C# :)

private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            Destroy(gameObject);
            StartCoroutine(Reset());
           
        }
    }

    IEnumerator Reset()
    {
        yield return new WaitForSeconds(4);
        LevelManager.instance.Respawn();
    }
}

标签: unity3dcoroutine

解决方案


这很简单,对象已经被销毁,所以Destroy(gameObject);下一帧之后的(脚本)将不起作用,正如我在评论中告诉你的那样,设置一个日志消息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 ..
}

推荐阅读