我有一个协程用于为光标设置动画。协程看起来像这样
private IEnumerator AnimateCursor(Vector2 targetScreenPoint)
{
while (true)
{
// Do animation stuff
Debug.Log(targetScreenPoint.ToString());
yield return null;
}
}
第一次启动协程时一切正常。如果光标移动,我将调用
StopCoroutine("AnimateCursor")
停止协程,然后使用targetScreenPoint
参数的新值再次启动协程。当我再次启动协程时,动画光标仍被绘制在其原始位置,并且
Debug.Log
同时打印targetScreenPoint
的第一个和第二个值(这就是为什么我认为协程在每个更新循环中执行两次的原因)。如果我将
StopCoroutine("AnimateCursor")
替换为StopAllCoroutines()
,则它可以正常工作,并且协程第二次启动时,它仅显示targetScreenPoint
的第二个值。有人知道发生了什么吗?
编辑:我错了关于在调试器运行时仍在设置动画的游标。我认为问题出在我的
StopCoroutine
,但我不知道为什么。如果协程接受参数,是否有一种特殊的方式必须停止协程? 最佳答案
您需要使用StartCoroutine("AnimateCursor", targetScreenPoint);
-字符串差异。
因为StopCoroutine("AnimateCursor")
仅在使用该字符串差异时才有效。
如果使用StartCoroutine(AnimateCursor(targetScreenPoint));
(即IEnumerator方差),则无法停止协程。