- Home /
Cant seem to destroy UI GameObject ive instantiated after each hit
This code is probably really bad, and ive been trying different ways for it to work. I instantiate a heart UI game object in a UI Panel and each time an enemy hits the "player" im trying to remove a heart. I can seem to call the destroy method but only one heart is destroyed. Ive tried different ways to count down in the hit code but it seems that its the destroy(gameobject) that i might of messed up. Again im not good at this but i keep trying to practice. i gave up after 3 weeks of trying xD (sorry if this is not setup correctly i dont use this feature often)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Health_UI : MonoBehaviour
{
public int health;//how much health
private int numOfHearts;//how many hearts
public List<Image> hearts = new List<Image>();
public Image spriteHeart;
public Transform panelTranform;
private GameObject heartsObject;
private void Awake()
{
numOfHearts = health;
HeartStartCaller();
}
void Start()
{
}
void Update()
{
if (health == 0)
{
Time.timeScale = 0;
}
}
private void HeartStartCaller()
{
for (int i = 0; i < numOfHearts; i++)
{
hearts.Add(spriteHeart);
}
foreach (var spriteHeart in hearts)
{
HeartHealth();
}
}
private void HeartHealth()
{
heartsObject = (GameObject)Instantiate(spriteHeart.gameObject, panelTranform);
//Instantiate(spriteHeart, panelTranform);
}
private void RemoveHealth()
{
Destroy(heartsObject);
Debug.Log("Destroy");
}
public void TakeDamage(int damage)
{
//when this number changes it changes the health value
health = health - damage;
Debug.Log(health + "health");
numOfHearts = health;// when health is 3 and u go to 2 it drops num hearts to 2
for (int i = numOfHearts ; i < hearts.Count; i++)
{
hearts.Remove(spriteHeart);
Debug.Log("Hearts count: " + hearts.Count);
RemoveHealth();
}
}
}
Comment
Best Answer
Answer by Hellium · Jun 14, 2021 at 09:45 PM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Health_UI : MonoBehaviour
{
[SerializeField] private GameObject heartPrefab;
[SerializeField] private Transform heartsParent;
[SerializeField, Min(1)] private int maxHealth = 10;
private int health;
// A Queue is a particular kind of "list"
// https://www.tutorialspoint.com/data_structures_algorithms/dsa_queue.htm
private Queue<GameObject> hearts = new Queue<GameObject>();
private void Awake()
{
health = maxHealth;
InstantiateHearts();
}
private void InstantiateHearts()
{
for (int i = 0; i < health; i++)
{
hearts.Enqueue(Instantiate(heartPrefab, heartsParent));
}
}
public void TakeDamage(int damage)
{
health = Mathf.Max(health - damage, 0); // Ensures the health does not go below 0
Debug.Log(health + "health");
while(damage > 0 && hearts.Count > 0)
{
Destroy(hearts.Dequeue());
damage--;
}
if (health == 0)
{
Time.timeScale = 0;
}
}
}