Question by
wreckerprogramming · Dec 09, 2017 at 08:54 AM ·
unity 5
Run more than expected number
Please do not get too hard about my grammar.
I write follow class for delay
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();
}
}
I receive 62 times the word update on the console. This problem will cause my next round of games to run 62 times, which slowed down my game.
Comment
Best Answer
Answer by Hellium · Dec 09, 2017 at 10:13 AM
The problem comes from the fact you are starting a new coroutine every frame while the 1st one has started. Just add a boolean to prevent the coroutine to be ran multiple times.
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();
}
}
Don't forget to accept the answer if it has helped you solving your problem.