【问题标题】:Set a class variable in IEnumerator coroutine在 IEnumerator 协程中设置类变量
【发布时间】:2025-12-06 02:05:03
【问题描述】:

我需要在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;
}

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

非常感谢!

【问题讨论】:

  • 您确定枚举器正在被完全枚举吗?即每件物品都被退回?如果在_bInitialized = true 上设置断点会发生什么?它会被执行吗?
  • 您也可以使用var enumerator = pInitialize(); while ( enumerator.MoveNext() ) { } 来枚举所有值。
  • @WaiHaLee 出于某种原因,VS 中的断点对我来说永远不会被击中。 IEnumerator 中的任何 Debug.Log 都将被忽略。感谢您的 MoveNext 提示。我先试试看。
  • 你应该尝试调试你的协程。如果协程中没有 Debug.Log 正在工作,你确定你的协程正在运行吗?
  • 这里可能发生的情况是你在协程中的代码在默默地抛出和捕捉异常,可能WiimoteManager中的部分代码与此有关。

标签: c# unity3d ienumerator


【解决方案1】:

我认为StartCoroutine 没有枚举所有值,无论出于何种原因。

由于Enumerator 懒惰地生成它的值,而不是所有的值都在生成,

_bInitialized = true;

永远不会被调用。

您可以通过添加来确认这一点

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

正如one of the comments Antoine Thiry 所建议的,

这里可能发生的情况是你在协程中的代码在默默地抛出和捕捉异常,可能WiimoteManager中的一些代码与它有关。

【讨论】:

  • 我认为您的 Wiimote 代码出现异常,这会停止 Corotuine 的执行。在 WiimoteManager.Cleanup(_wii); 之前做一个日志并在此语句之后查看日志是否出现。
  • @ZohaibZaidi 谢谢,它没有出现。我会先调查那里发生了什么。