- Home /
health code help
I was programming this health code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class hurt : MonoBehaviour
{
public GameObject img;
public GameObject img1;
public GameObject img2;
int h = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
switch (h)
{
case 1:
Destroy(img);
break;
case 2:
Destroy(img1);
break;
case 3:
Destroy(img2);
break;
}
}
void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("e"))
{
h = h + 1;
}
else
{
h = h + 0;
}
}
}
This code deletes hearts when I touch the enemy. but the order that the hearts delete is very inconsistent like sometimes it will delete the middle heart then last heart and not the first sometimes it will delete the first two but not the third. Then when I touch it again deletes the third why is this so inconsistent.
Answer by underkitten · Jan 13, 2021 at 10:04 PM
There is a possibility that multiple colliders enter at the same time and you "h" becomes 2 or even 3 after a touch. Try something like this: Instead of having 3 GameObjects, make a list, this will be useful if you decide to have more health. In Editor you can adjust how many hearts you want to have an slot them in in order (instead of slotting them in you can also Instantiate them but that's a different question). With each touch (collide) method Hit() will be called out and it will Destroy 1st heart in the list and also clear out 1st entry.
public List<GameObject> hearts = new List<GameObject>();
private void Hit()
{
Destroy(hearts[0]);
hearts.Remove(hearts[0]);
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "e")
{
Hit();
}
}
I would avoid putting stuff like Instantiate/Destroy etc in the Update() function because it checks for it every frame.
Your answer
![](https://koobas.hobune.stream/wayback/20220613023232im_/https://answers.unity.com/themes/thub/images/avi.jpg)