在Unity中使用协程时遇到了一个奇怪的问题。修改之前,我的代码如下:
IEnumerator Destory()
{
yield return new WaitForSeconds(destoryDelay);
yield return StartCoroutine(Timer.Start(0.5f, false, gameManager.EnableBtnSummon));
GameObject.Destroy(this.gameObject);
}
Run Code Online (Sandbox Code Playgroud)
Time.Start() 是我自己编写的实用程序,用于延迟调用。
public static IEnumerator Start(float duration, bool repeat, Action callback)
{
do
{
yield return new WaitForSeconds(duration);
if (callback != null)
callback();
} while (repeat);
}
Run Code Online (Sandbox Code Playgroud)
因为Time.Start()包含了WaitForSeconds(),所以我决定修改上面的代码如下:
IEnumerator Destory()
{
//yield return new WaitForSeconds(destoryDelay);
yield return StartCoroutine(Timer.Start(destoryDelay+0.5f, false, gameManager.EnableBtnSummon));
GameObject.Destroy(this.gameObject);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,控制台抛出错误:
ArgumentException:值不在预期范围内。
gameManager.EnableBtnSummon只是一个动作处理游戏逻辑。调试后,我确保该函数运行之前发生错误。但我将展示更多线索。
public void EnableBtnSummon()
{
//will not reach this!
print("Enable Button Summon");
//if detecting monster, change …Run Code Online (Sandbox Code Playgroud)