【问题标题】:Waiting for an event to finish before continuing in for loop在继续 for 循环之前等待事件完成
【发布时间】:2016-10-24 16:18:26
【问题描述】:

所以我在这部分被困了一段时间。 我正在编写一个项目,我有大约 12 轮相同的测试。 所以基本上我想要相同的功能,只是每次使用不同的头像。

有一个事件会触发,当它触发时会调用一个名为 FinishTest 的函数 我希望循环仅在 FinishTest 被触发并完成时继续。

for (int i = 0;  i < numberOfAvatars; i++) {
    StartTest(avatars[i]); // This is not really relevent to the question
    //Wait until the FinishTest event is finished before continuing the loop
}

当我的模型和某个对象之间有触发器时,FinishTest 被激活。 FinishTest 不可能在 startTest 之前完成,因为 StartTest 基本上实例化了模型,仅此而已,所以我认为不必有某种方法可以确保 StartTest 在 FinishTest 之前完成。

函数内部的内容并不重要,但为什么不重要:

private void  StartTest(GameObject avatar) {
        Instantiate(avatar, new Vector3(2f,2f,2f), Quaterion.identity));
}

private void FinishTest()
{
    testsResults[testNumber] = new TestResult(avatarsName, holdingObject); 
       testsResults[testNumber].setTimeUntilAvatarGotShot(string.Format("{0:F2}",timer) 

}

感谢您的帮助。

【问题讨论】:

  • 当您说事件时,您真的是指事件,或者您只想等待每个StartTest 调用完成,然后再继续for 循环?
  • 有一个单独的事件,当该事件触发时,它会调用同一个脚本中的一个名为 FinishTest 的函数。当真正的问题是 FinishTest 时,我不知道为什么我详细介绍了 StartTest
  • 哪里改了?为什么不修改问题并将其包含在内?
  • 已编辑以避免混淆
  • 向我们展示您的StartTest 事件是如何声明的,然后在哪里被调用。还有您问题中的代码,它们是否在协程函数中?现在,您没有任何代码与您的问题中的问题有关。这会降低您获得合理答案的机会。

标签: c# for-loop events unity3d coroutine


【解决方案1】:
bool TestFinished;
IEnumerator RunTest() {
    for (int i = 0;  i < numberOfAvatars; i++) {
        TestFinished = false;
        StartTest(avatars[i]); // This is not really relevent to the question

        //Wait until the FinishTest event is finished before continuing the loop
        while (!TestFinished) yield return null;
    }
}

private void FinishTest()
{
    testsResults[testNumber] = new TestResult(avatarsName, holdingObject); 
    testsResults[testNumber].setTimeUntilAvatarGotShot(string.Format("{0:F2}",timer);
    TestFinished = true;
}

然后你 StartCoroutine(RunTest()) 在你的代码某处。

【讨论】:

  • 谢谢 :) 做得很好。我的错误是在 IEnumertor 中使用 for 而不是 courutine 而不是 for 循环
猜你喜欢
  • 2020-07-14
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 2021-12-27
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多