Where to start a game demo and how to stop it when a key pressed?
HI, I am new to unity. So far I am enjoying it and have been able to make a table tennis game. I have a script for moving the bats. Now that the game is working properly I want the script to follow three work flows: 1. Play demo as soon as game launched. 2. Player one will play with AI when the Enter key was pressed 3. Player one will play with Player two when Insert key was pressed.
To get the work flows done I started the AI for both bats and make them play each other in the FixedUpdate method. This serves the purpose demo play. To play with AI I started a coroutine inside update method which take Enter key input. And to play with another player I started another coroutine inside update method that takes Insert key as the input.
void FixedUpdate(){
//codes to play demo
}
IEnumerator PlayerOneWithAI (){
// Codes for player one to play with AI
Debug.Log("PlayerWithAI mode enabled");
}
IEnumerator PlayerOneWithPlayerTwo (){
// Codes for two player play
Debug.Log("PlayerOneWithPlayerTwo mode enabled");
}
void update(){
if (Input.GetKey("enter"))
{
StartCoroutine("PlayerOneWithAI");
}
else if (Input.GetKey("insert"))
{
StartCoroutine("PlayerOneWithPlayerTwo");
}
}
Now when I play the game the demo starts fine. And when I pressed either Enter or Insert keys the demo dont stop. But I get those debug messages in the console. It seems the coroutines has started but the demo mode is not leaving the control of the bats from the FixedUpdate. What am I doing wrong? What could be the best way to get these work flows done? Also how am I supposed the start the demo again when the game is idle for some time? Thanks in advance for your helps.
Answer by LiloE · Feb 20, 2017 at 02:22 PM
It looks like the coroutines are overkill. What do you think of this classical solution?
void FixedUpdate() {
switch (state) {
case State.Demo:
// start player1 in demo mode
// start player2 in demo mode
break;
case State.OnePlayer:
// stop player1 if in demo mode
// start player2 in demo mode
break;
case State.TwoPlayers:
// stop player1 if in demo mode
// stop player2 if in demo mode
break;
default:
break;
}
}
void update() {
if (Input.GetKey("enter")) {
state = State.OnePlayer;
}
else if (Input.GetKey("insert")) {
state = State.TwoPlayers;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612111406im_/https://answers.unity.com/themes/thub/images/avi.jpg)