【发布时间】:2017-05-20 17:14:30
【问题描述】:
我需要的是每隔几秒增加一次玩家的统计数据,并且能够通过按下任何键来中断这个过程。
下面是我的协程。它一直在运行,有什么建议吗?
IEnumerator PlayerAction(PlayerStats playerStats, int incrementor1)
{
bool loop = true;
while (loop)
{
if (Input.anyKeyDown)
{
loop = false;
Debug.Log("Action is break");
yield break;
}
else
{
yield return new WaitForSeconds(2);
playerStats.Energy += incrementor1;
GameClock.Tic++;
Debug.Log("My first courutine is working!");
}
}
}
【问题讨论】:
-
你研究过停止协程的方法吗?您已经尝试过如何解决这个问题?
-
是的,我没有找到答案。我将检查移至更新并尝试使用 StopCourutine(),但它看起来是一个糟糕的解决方案。
-
@Kardux OP 想要跳出
while循环,如果您仔细查看`if (Input.anyKeyDown)` 代码。标题错误,但现已修复。 -
由于您使用
yield return,因此问题也可能与您的消费者代码有关。只有当您实际迭代返回的IEnumerator时,才会执行您的函数代码。你能展示一些吗? -
@grek40 这个问题已经解决了。那是因为 OP 使用了
yield return new WaitForSeconds(2),当if (Input.anyKeyDown)为真时它会错过帧。在我的回答下查看 OP 的评论。
标签: c# unity3d coroutine ienumerator