In my unity 2D project, i have the player avoiding missiles around a map.
I want the player to be able to take 3 hits before being taken to the losing screen.
However, i want to add a damage cooldown that prevents the player from taking multiple hits
within 2 second intervals. (So after recieving damage, the player becomes immune to damage for the following 2 seconds.)
This script feels correct to me, but there is obviously an error somewhere as it is not working.
Script in question:
using UnityEngine;
using System.Collections;
using System;
public class PlayerHealth : MonoBehaviour {
private int Playerhealth = 3; // This string holds the players current health value.
private bool DmgCD = true; // This string detects if the player can currently recieve damage
public Sprite[] Healths;
public GameObject healthbar;
void Start () {
}
void Update()
{
if (Playerhealth == 3)
{
healthbar.GetComponent<SpriteRenderer>().sprite = Healths[3];
}
if (Playerhealth == 2)
{
healthbar.GetComponent<SpriteRenderer>().sprite = Healths[2];
}
if (Playerhealth == 1)
{
healthbar.GetComponent<SpriteRenderer>().sprite = Healths[1];
}
if (Playerhealth == 0)
{
healthbar.GetComponent<SpriteRenderer>().sprite = Healths[0];
//Application.LoadLevel("Lose"); (Remove the comments from this when the lose level is finished) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
}
private IEnumerator HealthTracker()
{
while (true)
{
yield return new WaitForSeconds(2f);
DmgCD = true;
StopCoroutine(HealthTracker());
}
}
void OnCollisionEnter2D(Collision2D col) // When getting hit by a projectile with the enemy tag
{
if (col.gameObject.tag == "Missile")
{
//print("damage recieved");
if (DmgCD == true) //If the player is allowed to be damaged
DmgCD = false; // Make it so the player can no longer recieve new damage
Playerhealth = Playerhealth - 1;
StartCoroutine(HealthTracker());
}
}
}