Yield WaitForSeconds - Not waiting

Hey guys, I have started trying to learn C# for my first programming language and I am making a very basic game.

I have a script where the player takes damage and they lose 1 health point as long as they are colliding with the enemy. However the health point is taken off every frame rather then ever 3 seconds like I am aiming for. I have setup a IEnumerator function but I don’t understand why its not work.

Here is my code so far;

using UnityEngine;
using System.Collections;

public class Character : MonoBehaviour {

	public float health = 10;
	public int amount = 1;

	IEnumerator Immune(){
		Debug.Log ("Before waiting");
		yield return new WaitForSeconds (3);
		Debug.Log ("Finished waiting");
	}

	void ReceiveDamage( int amount) {
		health -= amount;
		Debug.Log("Recieved this amount of damage "+amount.ToString()+" now health="+health.ToString() );
			StartCoroutine("Immune");
		
		if( health <= 0)
		{
			Debug.Log("Destroy me");
			ProcessDeath();
		}

		
	}

	void ProcessDeath()
	{
		//Debug.Log("Process Death");
		Destroy(gameObject);
		
	}

	void OnCollisionStay2D(Collision2D coll) {
		if (coll.gameObject.tag == "Enemy")
						ReceiveDamage (amount);
	}

}

Any advice would be great!

Its waiting fine, there should be a 3 second delay between your two debug posts. :slight_smile:

Here is a solution.

private bool isImmune = false;

void ReceiveDamage( int amount) {
    if(!isImmune){
        health -= amount;
        StartCoroutine("Immune");
    }
    if( health <= 0){
        ProcessDeath();
    }
}

IEnumerator Immune(){
    isImmune = true;
    yield return new WaitForSeconds (3);
    isImmune = false;
}