I’m writing a game in C# and there’s a few times where I have to wait a second or two for something. So I’ve been using yield return new WaitForSeconds(1.5f);
However, if I put this in my OnTriggerEnter function, I need to have it defined as IEnumerator
instead of void
. This isn’t always acceptable, so I’m wondering if there’s some other way to wait for a specified amount of time without having to change the return type on the function I’m writing it in.
EDIT: I’ve tried creating an extra function that does the waiting, but it just seems to not actually wait for the time I’ve specified. Here’s the function:
IEnumerator wait(float time)
{
yield return new WaitForSeconds(time);
}
And here’s how I’ve called it:
changeColor(Color.red);
loseHealth(1); //lose health
canTakeDamage=false;
StartCoroutine(wait (1.5f));
Debug.Log ("done waiting");
changeColor(Color.white);
canTakeDamage=true;
The code is delaying when a player can be hit consecutively by an enemy. It also changes the colour to red when it can’t be hit, and back to white when it can be hit. When I try it this way, the colour never actually changes, and the player can take damage again immediately (rather than 1.5 seconds later).