- Home /
Best way to implement a turn system? Co-Routines or State-Machine?
For reference, I'm trying to recreate a concept similar to games like worms, territory war, or pocket tanks. The flow of the game should go back and forth from player 1 to player 2, taking timed turns, however, the timer should be able to be ended early if a player has finished their turn.
I have tried co-routines to setup a turn timer, however, I can't find a way to end the timer early if a player has finished with their turn. Would a state machine be a better way of handling this?
The flow should be similar to this:
Start player 1's turn
After x seconds OR if player 1 ends turn before time is up
Start player 2's turn
After x seconds OR if player 2 ends turn before time is up
Continue this until win conditions are met
What I have currently (crude outline) is:
IEnumerator Timer() {
while (true)
{
yield return new WaitForSeconds(60);
CheckWin();
EndTurn();
} }
void Start () {
StartCoroutine(Timer());
}
void Update () {
}
Answer by FuzzyLogic · Mar 01, 2018 at 12:30 AM
A coroutine is the appropriate solution. You can stop a coroutine with the StopCoroutine()
method. StartCoroutine() returns an ID that refers to the coroutine that was activated, which you can pass to StopCoroutine() when you want to kill it.
Coroutine timerID = null;
IEnumerator Timer() {
// while (true) { // infinite loops are BAD!
while (timerID != null) {
yield return new WaitForSeconds(60);
if (CheckWin() || EndTurn()) {
timerID = null;
}
}
}
void Start () {
timerID = StartCoroutine(Timer());
}
void Update () {
if (EndTurnButtonPressed()) {
StopCoroutine(timerID);
CheckWin();
EndTurn();
}
}
There's no need to use Update at all. You can read input inside a coroutine as well. The whole sequence of actions can be handled inside a coroutine. Usually you don't want any input to interrupt the execution of the current turn. By placing the input checking inside the coroutine you can avoid unwanted interruptions
while (true)
{
while (!Input.GetButtonDown($$anonymous$$eyCode.Return))
yield return null;
// this will execute when the Return key is pressed
}
Though for a "timed" input handler you may want to create a CustomYieldInstruction that combines a timer with some input checking. Though it highly depends on what kind of input the user interacts with.
Because of delays with yields, a coroutine is probably not the best place to handle input if you want it to be responsive. Generally you want input to be polled as often as possible for twitch reaction.
Your answer

Follow this Question
Related Questions
rpg turn based attack enemy is not attacking 1 Answer
Where can I find Memory Game Demo package? 1 Answer
Mecanim-Statemachine caches old version? (was: One Transition blocks other Transitions) 0 Answers
Transition Between Different Player States In Animator 0 Answers
Mecanim - State Behavior - Select motion clip to play at runtime 0 Answers