Hello, i want to run a bot-script every time the player makes a move. The Player move sets the bool WhosTurn to false, which should run the bot. It works from a start, but after the first player move, the coroutine keeps running, even though it itself states the bool to be true, which should end the if.
void Update()
{
//Debug.Log(GameControl.WhosTurn);
new WaitForSeconds(3f);
if (GameControl.WhosTurn != true)
{
if (GameControl.Player == "White") { status = "Black"; }
else { status = "White"; }
new WaitForSeconds(3f);
GameControl.WhosTurn = true;
StartCoroutine (BotMove());
}
}
Printing the bool WhosTurn even gives me “true”, so the bot-coroutine shouldn’t keep running, what am i doing wrong??
Hey and welcome to the forum,
The problem you have here is that there is no routine running. There is no wait taking place at all.
A coroutine will only work as you want it if you have an extra function that looks like this where the WaitFor is used together with yield return:
IEnumerator SomeCoroutineToDoStuff() {
yield return new WaitForSeconds(3f); //wait for frame in 3 seconds until we resume here
yield return null; //wait for next frame
}
Additionally this function must be started with
StartCoroutine(SomeCoroutineToDoStuff());
Only then the yield statements will correctly function.
This being said i’d suggest the following as a rule that will help you in your scripts:
Update
is a place to do things that have to be done every frame. These are things like
- check if a button was pressed
- count down a timer
- move an object
All other things like Starting Coroutines and so on should not be in Update
. Instead at the point where you set the value of GameControl.WhosTurn
there should be a call to the script that your current logic is in where this current logic is in some function so that it can be executed once when it has to be executed.
This makes things easier to understand what is happening when and where as there is always a direct chain of functions that you can follow.
Additionally it is better for performance as you don’t do these checks every frame. On top of that it is safer - your current setup contained an error which led to a script which potentially spawned a new Coroutine BotMove
every frame.
Let me know if something was unclear or if this helped you.