【问题标题】:Wait inbetween functions in Unity3D在 Unity3D 中的函数之间等待
【发布时间】:2015-07-06 07:53:56
【问题描述】:

我想在Start()Update()函数之间等待2秒,我的代码:

void Start () {
        r = GetComponent<RobotController>();
        r.postEffectroPos(new Vector3(0.2f, 0.0f, 0.3f), 0.1f);
        StartCoroutine(wait2Sec());
    }

我的等待函数:

IEnumerator wait2Sec() {
        yield return new WaitForSeconds(2.0f);
        Debug.Log("Robot is moving to start position");
    }

在更新()中:

if (controlRobot)
        {
            moveRobot();
            movePlayerToRobot();
        }

我想在开始时将我的机器人移动到设定位置,然后启用机器人的移动。问题是moveRobot() 获取了机器人的当前位置,并根据输入发布了一个调整位置的调用。

因此机器人不会在 Update() 函数中等待 Start() 函数完成 2 秒。

【问题讨论】:

    标签: c# unity3d yield-return


    【解决方案1】:

    Update 函数的调用独立于Start 方法。我能想到的推迟 Update 方法的唯一方法是阻止 UI 线程,您应该永远不要这样做

    实现您想要的一种方法是在MonoBehaviour 上设置一个标志,该标志从内部开始设置为true,并在Update 方法中检查该标志。像这样的:

    class Robot:MonoBehaviour
    {
      bool shouldMove = false;
    
      void Start () {
        r = GetComponent<RobotController>();
        r.postEffectroPos(new Vector3(0.2f, 0.0f, 0.3f), 0.1f);
        StartCoroutine(wait2Sec());
      }
    
      IEnumerator wait2Sec() {
        yield return new WaitForSeconds(2.0f);
        Debug.Log("Robot is moving to start position");
        shouldMove = true;
      }
    
      void Update()
      {
        if (controlRobot && shouldMove)
        {
            moveRobot();
            movePlayerToRobot();
        }
      }
    }
    

    注意:我没有为此使用controlRobot,因为我不知道它的用途,但如果出于相同原因使用它,只需将controlRobot 设置为wait2Sec

    【讨论】:

      猜你喜欢
      • 2021-02-25
      • 1970-01-01
      • 2020-07-18
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      相关资源
      最近更新 更多