- Home /
I need help with the player's health points
(I'm sorry if my writing sounds weird. I hope it's coherent enough to get my point across.) I was following a tutorial by BlackThornProd for hearts to represent the players health instead of using a health bar. The problem I'm having is that I'm not sure how to make it so that when the player collides with an enemy that they lose a heart.
Health Script: {
public int health;
public int numOfHearts;
public Image[] hearts;
public Sprite fullHeart;
public Sprite emptyHeart;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (health > numOfHearts)
{
health = numOfHearts;
}
for (int i = 0; i < hearts.Length; i++)
{
if(i < health)
{
hearts[i].sprite = fullHeart;
}
else
{
hearts[i].sprite = emptyHeart;
}
if(i < numOfHearts)
{
hearts[i].enabled = true;
}
else
{
hearts[i].enabled = false;
}
}
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Enemy")
{
//I'm not sure what to put here.
}
}
}
If you need anymore information, let me know. Thank you.
Answer by kylecat6330 · Jun 30, 2020 at 03:51 PM
It seems like all you would need to do is subtract 1 health.
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Enemy")
{
health -= 1;
Debug.Log("Enemy Collision Detected");
}
}
If that does not work then make sure you get the "Enemy Collision Detected" message. If you do not then there is a problem with the collision detection. If it works you can remove Debug.Log("Enemy Collision Detected");
Thank you so much! I knew it was a simple solution, but for the life of me I couldn't remember.