Basically, if Object A gets collided by Object B, Object A should be invulnerable for 3 seconds before being able to be vulnerable. Invulnerability is a variable attached to Object A. The following is the code to detect collisions and to toggle invulnerability, and is attached to Object B. The Yield WaitForSeconds does not work for some reason. I’m able to Debug upto “before waiting 3 seconds”. What am I doing wrong ?
IEnumerator OnTriggerEnter2D(Collider2D radiusCollisionCheck)
{
if (!GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerDamage> ().invulnerable)
{
if (radiusCollisionCheck.gameObject.tag == "Crowd")
{
GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerHealth>().DamagePlayer(26);
GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerDamage>().invulnerable = true; // disallow further damage
Debug.Log ("before waiting 3 secs");
yield return new WaitForSeconds (3); // wait for the specified damage timeout
Debug.Log ("waited 3 secs");
GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerDamage>().invulnerable = false;
}
} else
{
Debug.Log ("Player is invulnerable");
}
}
The simplest way to limit your coroutine from being called multiple times is to just use a Boolean flag that you set inside the coroutine which will, if it’s set, prevent the coroutine’is body from being executed when set. Then simply unset the Boolean when the initially initiated coroutine is finished, opening it back up for re-entry.
Of course there are more elegant methods of achieving this, but this is probably the best starting point in your understanding of coroutine’is.