为什么这个 Coroutine 只 运行 一次?
Why does this Coroutine only run once?
"Something"只打印一次...
IEnumerator printSomething;
void Start () {
printSomething = PrintSomething();
StartCoroutine (printSomething);
}
IEnumerator PrintSomething () {
print ("Something");
yield return null;
StartCoroutine (printSomething);
}
尝试用协同例程的名称代替指针。或者协程本身。
IEnumerator PrintSomething ()
{
print ("Something");
yield return null;
StartCoroutine ("PrintSomething");
}
或者
IEnumerator PrintSomething ()
{
print ("Something");
yield return null;
StartCoroutine (this.PrintSomething());
}
您的方法的错误在于您保存了枚举器。枚举器已经是 "enumerating" 因此将枚举器提供给 StartCoroutine
方法两次基本上会导致协程直接退出,因为枚举器之前已经被使用过。再次调用函数即可再次启动协程
StartCoroutine(PrintSomething());
但不要一遍又一遍地启动协程,而是尝试在内部使用循环。
while (true)
{
print("something");
yield return null;
}
这更好,因为协程的内部处理及其开销未知。
我 运行 进入这个完全相同的问题,Felix K. 是正确的,因为它假设 IEnumerator 已经 运行 并且立即 returns。我的解决方案是传递函数本身,以便在每次调用它时生成一个新的 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;
}
"Something"只打印一次...
IEnumerator printSomething;
void Start () {
printSomething = PrintSomething();
StartCoroutine (printSomething);
}
IEnumerator PrintSomething () {
print ("Something");
yield return null;
StartCoroutine (printSomething);
}
尝试用协同例程的名称代替指针。或者协程本身。
IEnumerator PrintSomething ()
{
print ("Something");
yield return null;
StartCoroutine ("PrintSomething");
}
或者
IEnumerator PrintSomething ()
{
print ("Something");
yield return null;
StartCoroutine (this.PrintSomething());
}
您的方法的错误在于您保存了枚举器。枚举器已经是 "enumerating" 因此将枚举器提供给 StartCoroutine
方法两次基本上会导致协程直接退出,因为枚举器之前已经被使用过。再次调用函数即可再次启动协程
StartCoroutine(PrintSomething());
但不要一遍又一遍地启动协程,而是尝试在内部使用循环。
while (true)
{
print("something");
yield return null;
}
这更好,因为协程的内部处理及其开销未知。
我 运行 进入这个完全相同的问题,Felix K. 是正确的,因为它假设 IEnumerator 已经 运行 并且立即 returns。我的解决方案是传递函数本身,以便在每次调用它时生成一个新的 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;
}