An alternative way to write a timer in Unity (and in my opinion much simpler) is with coroutines. It would be something like this (in EnemyAI
):
// No need for Update function at all in this case.
void TurnSystem_OnTurnChanged() {
if (TurnSystem.Instance.IsHumanTurn()) {
return;
}
StartCoroutine(WaitAndEndTurn(2f));
}
IEnumerator WaitAndEndTurn(float waitTime) {
yield return new WaitForSeconds(waitTime);
TurnSystem.Instance.NextTurn();
}
Note though that coroutines are not threads - they still run in the main event loop on the same thread. Just every time yield
is called, the control is given back to the event loop (somewhat like in cooperative scheduling) and it gets called again (continuing from where it yielded) the next time only when whatever condition we gave it has passed (or on the next frame if it was yield return null;
).
IMO, they are oftentimes very useful for making the code less cluttered.