协程函数在WaitForSeconds停止

时间:2018-07-27 22:05:02

标签: c# unity3d

我的协程功能只工作一次。 _isPaused变量为true。找不到我做错了。

IEnumerator Movement() 
{
    while (_isPaused) // I checked, it's true
    {  
        Debug.Log("Some action");
        yield return new WaitForSeconds(0.8f);
    }
}

void Update () 
{
    if (Input.GetKeyDown(KeyCode.P)) 
    {
        StartCoroutine(Movement());
    }
}

Here是完整的代码:

2 个答案:

答案 0 :(得分:3)

这是您的代码:

while (_isPaused) 
{  
    Debug.Log("Some action");
    yield return new WaitForSeconds(0.8f);
}

您的while循环到达WaitForSeconds时将暂停。由于您在按下“ P”时在代码中的某个位置将Time.timeScale设置为0,因此它将暂停。这是正常现象。这样做是为了使您可以使用Time.timeScale暂停协同程序功能。将Time.timeScale设置回1后,它会自动继续运行。


如果您不希望Time.timeScale在等待WaitForSeconds时暂停协程功能,请使用WaitForSecondsRealtime而不是WaitForSeconds

while (_isPaused) 
{
    Debug.Log("Some action");
    yield return new WaitForSecondsRealtime(0.8f);
}

这是因为WaitForSeconds是通过Time.deltaTime或类似的属性实现的,当0设置为Time.timeScale时,该属性也会变为0,从而导致计时器暂停而WaitForSecondsRealtime是用Time.realtimeSinceStartup实现的,而根本不受Time.timeScale的影响。

答案 1 :(得分:0)

没有程序的全部代码,很难分辨出什么地方出了问题。我建议您使用 true

测试协程
for i in indices:
    mat_trans[:, i] = rank_vec

代替使用 _isPause 字段。

相关问题