Problem with hit detection and corountines
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());
}
}
}
Answer by oussama_bonnor · Mar 29, 2017 at 12:58 AM
Why are you using the while(true) loop ? you can call the WaitForSeconds fonction once and then change the boolean variable's state. without stopping the coroutine and stuff. Can you say what s going on when you run it ?
I did not think waitforseconds worked without being in a courontine? Could you give me an example of this working please?
As for whats currently going on with the loop, it is working correctly, but ignoring the waitforseconds part.
Your loop is ignoring the waitForSeconds cause ur stoping the coroutine..delete that line that stops it and it should work fine (sorry for the late answer)
Your answer
Follow this Question
Related Questions
Can you guys help me with my health/damage system? 0 Answers
OnCollisionEnter2D message being ignored 1 Answer
Damage Over Time problem 2 Answers
My enemy don't take damage. 1 Answer