I have an Player Health script that I need help with. In my game the player should only be able to be damaged by one point at a time, but upon collision my health is damage multiple times in one second of collision. How do I delay the function being called?
Here is my script:
public class PlayerHealth : MonoBehaviour
{
public int Health = 10;
public int AttackDamage = 1;
void damaged()
{
Health = AttackDamage-Health;
}
void OnCollisionEnter2D(Collision2D collision)
{
if (GameObject.FindWithTag("Damaging"))
{
damaged();
}
}
void Update()
{
if(Health > 10)
{
Health = 10;
}
if(Health <= 0)
{
FindObjectOfType<GameManager>().GameOver();
}
}
}
This will work.
private bool scriptAlreadyRan = false;
if(Health <= 0 && !scriptAlreadyRan)
{
scriptAlreadyRan = true;
FindObjectOfType<GameManager>().GameOver();
}
P.S. - This is a really dirty way of doing it since you are checking each frame if the player died; Instead, whenever the player takes damage, check if his HP is <= 0 now, and if it is, call the game over method.
Thanks that makes a lot more sense. Checking only when the player is damaged. but that isn’t the part of the script that is called for more than twice. it’s the Damage function on collision. The scripts calls on the game manager perfectly fine.
Oh I see. Sorry.
GameObject.FindWithTag(“Damaging”) is actually finding a game object with this tag and, in your case, checking if its null, if it isn’t it’s calling the damage() method. Try replacing it with either
collision.gameObject.CompareTag("Damaging")
or
collision.gameObject.tag == "Damaging"
My guess is that you were hitting two objects or you had this script attached to the same object twice.
Unity - Scripting API: WaitForSeconds This may help you can literally do a timed pause for the function before it can be called again