I am trying to get a moving platform code to wait for a couple of seconds after reaching one end. Unfortunately, my code isn’t working, and I’ve already looked around for general tips.
void OnTriggerEnter(Collider other) {
if (other.tag == "Target") {
StartCoroutine (PauseAndTurn ());
}
}
IEnumerator PauseAndTurn () {
if (direction == directionBase) //if this if/else statement is below the WaitForSeconds(2), then it doesn't run at all for some reason and the platform just keeps going
direction = -direction;
else
direction = directionBase;
yield return new WaitForSeconds (2);
}
The platform just doesn’t wait for some reason. Any ideas?
I assume you move your Platform in your Update()- or FixedUpdate()-Method?
Then you should introduce a boolean, like
private bool moving;
And check if it is true every time before you allow the object to move in Update()/FixedUpdate().
Now change PauseAndTurn to:
IEnumerator PauseAndTurn() {
if(direction == directionBase)
direction = -direction;
else
direction = directionBase;
moving = false;
yield return new WaitForSeconds(2);
moving = true;
}
For your understanding, WaitForSeconds() does not mean, the Component/the Script will stop doing anything at all for n seconds. It just makes the Coroutine itself wait.