为什么这个协程只运行一次?

问题描述 投票:1回答:3

“内容”仅打印一次...

IEnumerator printSomething;

void Start () {

    printSomething = PrintSomething();
    StartCoroutine (printSomething);

}

IEnumerator PrintSomething () {

    print ("Something");

    yield return null;
    StartCoroutine (printSomething);

}
c# unity3d ienumerator
3个回答
2
投票

您的方法中的错误是您保存了枚举数。枚举器已经在“枚举”,因此将枚举器两次赋予StartCoroutine方法基本上会导致协程直接退出,因为之前已使用了该枚举器。可以通过再次调用该函数来再次启动协程。

StartCoroutine(PrintSomething());

但是不要一遍又一遍地启动协程,而应尝试在内部使用循环。

while (true)
{
    print("something");
    yield return null;
}

这更好,因为协程的内部处理及其开销是未知的。


1
投票

请尝试使用例程的名称而不是指针。或协同例程本身。

IEnumerator PrintSomething () 
{
    print ("Something");

    yield return null;

    StartCoroutine ("PrintSomething");
}

IEnumerator PrintSomething () 
{
    print ("Something");

    yield return null;

    StartCoroutine (this.PrintSomething());
}

0
投票

我遇到了完全相同的问题,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;
}
© www.soinside.com 2019 - 2024. All rights reserved.