在 IEnumerator 协程中设置一个 class 变量

Set a class variable in IEnumerator coroutine

我需要在 Update() 中做一些初始化工作。

这个初始化工作需要一些时间,在这个初始化完成之前我无法继续Update()中的常规代码。

此外,此初始化需要一些 WaitForSeconds() 才能工作。

因此我尝试了以下方法:

private bool _bInitialized = false;
private bool _bStarted = false;

void Update()
{
    if (!_bInitialized)
    {
         if (!_bStarted)
         {
             _bStarted = true;
             StartCoroutine(pInitialize());
         }
         return;
    }

    (...) do stuff that can only be done after initialization has been completed
}

但是,我似乎无法更改 IEnumerator 中的变量 _bInitialized

_bInitialized 永远不会变成 true:

private IEnumerator pInitialize()
{
    WiimoteManager.Cleanup(_wii);
    yield return new WaitForSeconds(2);

    _wii = WiimoteManager.Wiimotes[0];
    yield return new WaitForSeconds(2);

    _wii.SetupIRCamera(IRDataType.BASIC);
    yield return new WaitForSeconds(2);

    _bInitialized = true; //this doesn't seem to work
    yield return 0;
}

谁能告诉我如何正确地做到这一点?

非常感谢!

我认为 StartCoroutine 出于某种原因并未列举所有值。

由于 Enumerator 延迟生成其值,并且并非所有值都已生成,

_bInitialized = true;

从未调用过。

您可以通过添加

来确认这一点
var enumerator = pInitialize(); while ( enumerator.MoveNext() )
{
    // do nothing - just force the enumerator to enumerate all its values
}

by Antoine Thiry

中的建议

What may happen here is that your code in the coroutine is silently throwing and catching an exception, maybe some of the code in WiimoteManager has something to do with it.