gpt4 book ai didi

c# - "OnCollisionEnter()"中的协程 (WaitForSeconds()) 给出编译错误

转载 作者:太空宇宙 更新时间:2023-11-03 17:38:06 27 4
gpt4 key购买 nike

我正在尝试制作一款平台游戏,我想在 x 秒后禁用平台重力。但是它给出了一个编译错误,它不能被使用,因为 void 不是内部接口(interface)类型。

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

// Make platforms fall
yield return new WaitForSeconds(2f);
collision.rigidbody.useGravity = enabled;
yield return null;
}

最佳答案

您只能在 coroutine 函数中产生。您不能从 void 函数。一些 Unity 回调函数,例如 Start 函数,可以设为 void 或协程函数。幸运的是,OnCollisionEnter 函数就是其中之一,因此只需将 void 更改为 IEnumerator。这将在不需要手动启动新协程函数的情况下工作。 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;
}

关于c# - "OnCollisionEnter()"中的协程 (WaitForSeconds()) 给出编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50024846/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com