[英]Why does this Coroutine only run once?
“某事”只打印一次......
IEnumerator printSomething;
void Start () {
printSomething = PrintSomething();
StartCoroutine (printSomething);
}
IEnumerator PrintSomething () {
print ("Something");
yield return null;
StartCoroutine (printSomething);
}
您的方法的错误在于您保存了枚举器。 枚举器已经在“枚举”,因此两次将枚举器提供给StartCoroutine
-方法基本上会导致协程直接退出,因为之前已经使用过枚举器。 再次启动协程可以通过再次调用该函数来完成。
StartCoroutine(PrintSomething());
但是不要一遍又一遍地启动协程,而是尝试在内部使用循环。
while (true)
{
print("something");
yield return null;
}
这更好,因为协程的内部处理及其开销是未知的。
尝试使用协程的名称而不是指针。 或者协程本身。
IEnumerator PrintSomething ()
{
print ("Something");
yield return null;
StartCoroutine ("PrintSomething");
}
要么
IEnumerator PrintSomething ()
{
print ("Something");
yield return null;
StartCoroutine (this.PrintSomething());
}
我遇到了这个完全相同的问题,Felix K. 是正确的,因为它假定 IEnumerator 已经运行并立即返回。 我的解决方案是传递函数本身,以便在每次调用它时生成一个新的 IEnumerator。 我希望这可以帮助别人!
public IEnumerator LoopAction(Func<IEnumerator> stateAction)
{
while(true)
{
yield return stateAction.Invoke();
}
}
public Coroutine PlayAction(Func<IEnumerator> stateAction, bool loop = false)
{
Coroutine action;
if(loop)
{
//If want to loop, pass function call
action = StartCoroutine(LoopAction(stateAction));
}
else
{
//if want to call normally, get IEnumerator from function
action = StartCoroutine(stateAction.Invoke());
}
return action;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.