"OnCollisionEnter()"中的Coroutine(WaitForSeconds())给出编译错误

Ger*_*abó 1 c# unity-game-engine

我正在尝试制作一个平台游戏,我想在x秒之后恢复平台的重力.但它提供了一个无法使用的complile错误,因为void不是内部接口类型.我是个笨蛋,我迫不及待地继续我的项目.谢谢你的时间,我很抱歉我糟糕的英语.

 private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.name == "Platform(Clone)")
    {
        numberOfJumps = 2;
        Debug.Log("Platform hit");
    }

    //Maake platforms fall
    yield return new WaitForSeconds(2f);
    collision.rigidbody.useGravity = enabled;
    yield return null;
}
Run Code Online (Sandbox Code Playgroud)

Pro*_*mer 6

你只能在一个coroutine函数中屈服.你不能从一个void功能.一些Unity回调函数就像函数一样Start可以成为void函数或协程函数.幸运的是,该OnCollisionEnter功能是其中之一,所以只需更改 voidIEnumerator.这将无需手动启动新的协同程序功能.当发生碰撞时,Unity会自动调用并作为协程启动它.

private IEnumerator OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.name == "Platform(Clone)")
    {
        numberOfJumps = 2;
        Debug.Log("Platform hit");
    }

    //Maake platforms fall
    yield return new WaitForSeconds(2f);
    collision.rigidbody.useGravity = enabled;
    yield return null;
}
Run Code Online (Sandbox Code Playgroud)