In a certain script (called GameManager), I have a coroutine that looks something like this:
public IEnumerator StartDelay()
{
yield return new WaitForSeconds(delay1);
DeactivateAllActors(); //Does some stuff
yield return new WaitForSeconds(delay2);
StartGame(); //Does some other stuff
gameStarted = true; /*Should be detected by other scripts instantly, but that doesn't happen*/
}
The coroutine is called from the start function. Now the issue lies in the last line of the coroutine (gameStarted = true). I expected this statement to run right after the call to the StartGame() function. I have 2 other scripts that rely on this boolean value to work properly. But for some reason, one of those scripts can’t instantly detect that ‘gameStarted’ has been set to ‘true’. Here’s what the script looks like (let’s assume it’s called ScoreManager):
if (gameManager.gameStarted) //gameManager is an object of GameManager
{
scoreCount++;
scoreText.text = "Score: " + Mathf.Round(scoreCount);
if (scoreCount > hiScoreCount)
{
hiScoreCount = scoreCount;
HiScoreText.text = "Best: " + Mathf.Round(hiScoreCount);
SavingScript.SaveGame(this);
}
}
After the StartGame() function in GameManager finishes running, it actually takes a few seconds for ScoreManager to detect that ‘gameStarted’ has been set to true. I have no idea why. But I have a feeling it might have something to do with the coroutine. I’m pretty sure it would work just fine if I used a timer instead.
And it is hard to determinate where you made your mistake, since you failed to describe when and how you call the if (gameManager…blablabla… portion.
Coroutines are fake multi-threading. You get something like this:
Start method (gameStarted == false)
StartDelay method (gameStarted == false)
— yield return for delay1 seconds
— some other code run while the ~delay1 time passes (possibly your other check code is seeing the gameStarted == false)
— after delay1 time
StartDelay method (gameStarted == false)
— DeactivateAllActors();
— yield return with delay2 second (gameStarted still false)
— some other code run while the ~delay2 time passes (may include your other, checking code, gameStarted is still false)
— after delay2 time
StartDelay method (gameStarted == false)
---- StartGame();
---- set gameStarted = true and return from the StartDelay() method for good
From now on your application sees gameStarted == true.
By timer, I was referring to creating a float value that increases by 1 every second (via Time.deltaTime).
Either way, I think I’ve figured out why the ScoreManager wasn’t detecting the change in gameStarted. I still need some time to test it before I can verify.