运行超过预期的数量

时间:2017-12-08 10:03:06

标签: c# unity3d

请不要对我的语法太过刻薄。

我写下延迟课程

public class Queue_System_Of_Begin_Game : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

        if (Game_Controller.Player1_First_throws_true && Game_Controller.Player2_First_throws_true)
        {

            StartCoroutine(ExecuteAfterTime(1));

        }

    }
    //--------------------------------------
    public GameObject player1_icon, player2_icon, dice1_p1, dice2_p1, dice1_p2, dice2_p2;
    void determine_the_turn()
    {
        Debug.Log("update");

    }

    IEnumerator ExecuteAfterTime(float time)
    {
        yield return new WaitForSeconds(time);

        determine_the_turn();
    }
}

我在控制台上收到了62次单词更新。 这个问题将导致我的下一轮比赛运行62次,这减缓了我的比赛。

2 个答案:

答案 0 :(得分:2)

每帧调用 Update()方法一次,这就是你获得62次“更新”的原因。

你可以尝试添加一个布尔值,这样它只会被调用一次:

bool ischecked = false;
void Update(){
    if (!ischecked){
        if (Game_Controller.Player1_First_throws_true && Game_Controller.Player2_First_throws_true) {
            ischecked = true;
            StartCoroutine (ExecuteAfterTime (1));
        }
    }
}

答案 1 :(得分:-1)

我找到了解决问题的方法。我必须在我的if commond中使用一个布尔变量:

public class Queue_System_Of_Begin_Game : MonoBehaviour
  {
      private bool coroutineStarted;

      // Update is called once per frame
      void Update()
      {     
          if (!coroutineStarted && Game_Controller.Player1_First_throws_true && Game_Controller.Player2_First_throws_true)
          {
              coroutineStarted = true ;
              StartCoroutine(ExecuteAfterTime(1));     
          }     
      }
      //--------------------------------------
      public GameObject player1_icon, player2_icon, dice1_p1, dice2_p1, dice1_p2, dice2_p2;
      void determine_the_turn()
      {
          Debug.Log("update");

      }

      IEnumerator ExecuteAfterTime(float time)
      {
          yield return new WaitForSeconds(time);

          determine_the_turn();
      }
  }