- Home /
How can I use a co-routine to yield player damage?
Hi, I am trying to use a co-routine to make my player invulnerable to damage for a few seconds after being hit. I tried the following code, but the player can still constantly take damage. Any suggestions would be great! Thanks!
I have my private bool invul = false; then...
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Enemy") { // If colliding with enemy, execute this block
HealthScript playerHealth = this.GetComponent<HealthScript> (); //get player health script
playerHealth.Damage (1); //damage player
invul = true; //player is invulnerable
animator.SetTrigger ("Hit"); //play hit animation
StartCoroutine (InvulWait ());
}
}
private IEnumerator InvulWait() {
yield return new WaitForSeconds (2); //invul time
invul = false;
}
}
Answer by robertbu · Sep 27, 2014 at 02:39 AM
Assuming this is the only point where damage is given, you need to change line 3:
if (!invul && collision.gameObject.tag == "Enemy") { // If colliding with enemy, execute this block
Thanks! That works perfectly. Now to figure out how to get my trigger to stop repeating during the invulnerable time. If I can't, I guess that would be best posted in a new question since I marked this one answered :)
Actually the checkmark to the left of the question is used to mark a question as answered. As for your second issue, I don't do much with the animation system. Unless you did rewriting, the code I suggested avoids calling 'animator.SetTrigger()' on line 7, so I don't know what is causing your problem. Any chance your animation is looping?
Whoops, got the answer checked this time. I tried to move the 'animator.SetTrigger()' into the co-routine, but that didn't seem to help. I did double-check to make sure the animation isn't looping and the length of the animation is sufficient. The damage has yielded during the invulnerability time, but the trigger can be activated in rapid succession when the player collides with a moving enemy.