【发布时间】: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