Health is not lowering right?
Hello! I want that my player loses health if he enters the trigger of an enemy. I got the script, but somehow, the player always loses 2 life, instead of 1! If I put higher numbers in, he loses higher values, but he never lose 1 hp. Can somebody help me out here?
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class Health : MonoBehaviour { public int playerHealth; public int numberOfHearts;
public Image[] hearts;
public Sprite fullHeart;
public Sprite emptyHeart;
public Rigidbody2D rb;
public bool gotHit;
private float thrust = 100.0f;
private void Start()
{
gotHit = false;
}
void Update()
{
if (playerHealth > numberOfHearts)
{
playerHealth = numberOfHearts;
}
for (int i = 0; i < hearts.Length; i++)
{
if(i < playerHealth)
{
hearts[i].sprite = fullHeart;
}
else
{
hearts[i].sprite = emptyHeart;
}
if(i < numberOfHearts)
{
hearts[i].enabled = true;
}
else
{
hearts[i].enabled = false;
}
}
}
void OnTriggerEnter2D(Collider2D other)
{
WasAttacked();
if (other.gameObject.tag == "Enemy")
{
if (gotHit == true)
{
Debug.Log("Got Hit!");
playerHealth -= 1;
rb.AddForce(transform.position - other.transform.position * thrust);
}
}
}
void OnTriggerExit2D(Collider2D other)
{
Escaped();
}
private void WasAttacked()
{
gotHit = true;
}
private void Escaped()
{
gotHit = false;
}
}
Your answer
Follow this Question
Related Questions
KillPlayer, Null Reference Exception. 2 Answers
Same script on two objects, only first one works 1 Answer
Corgi Engine - Character glitches with "jump" animation on top of a ladder 0 Answers
2D player hides behind the room setting 2 Answers
Unexpected symbol '=' parser error and Unexpected symbol '(' error 1 Answer