Am I using this Coroutine and IEnumerator correctly?
When a player clears a level on my game I want to wait for 5 seconds before loading the next level so they can see their score... or whatever they want to do in that time.
My concern is that in the sample code in the documentation the coroutine is being called from the start method, so it's only called once. I'm calling mine from the update method, so I'm concerned that I'm spawning a whole bunch of coroutine objects or some such. I mean the code works in that it does what I want it to do, but the debug logic I added shows that the coroutine is being called every frame until the 5 seconds has passed, then it falls through the yield return statement and loads the next level.
Am I supposed to be adding some logic to the update statement to ensure the coroutine is only called once?
void Update()
{
if(levelCleared)
{
StartCoroutine(ShowScore());
Debug.Log("started a coroutine");
}
else
{
currentTime = Time.time - startTime;
timeScore.text = currentTime.ToString("F1");
}
IEnumerator ShowScore()
{
Debug.Log("running ShowScore");
yield return new WaitForSeconds(5);
Debug.Log("five seconds has passed");
SceneManager.LoadScene(Mathf.Clamp(SceneManager.GetActiveScene().buildIndex + 1, 0, levels), LoadSceneMode.Single);
}
}
Answer by Nishchhal · Apr 01, 2019 at 03:40 AM
You can make it run once using a Simple Boolean Lock to check if it is already running or not.
bool switchingLevel = false; if(levelCleared && !switchingLevel) { StartCoroutine(ShowScore()); }
IEnumerator ShowScore() { switchingLevel = true; //Put your ShowScore Logic Here }