Destroy Instantiated GameObject

Hi, I’m trying to create a health system. Basically I instantiate 3 prefabs which are hearts displaying how much health the player has. I’m having trouble using Destroy(); to remove them once they are instantiated. I’ve removed a lot of code that isn’t really relevant.

public class healthControl : MonoBehaviour {

	public int health;
	public GameObject heart3p;
	private GameObject heart3;

	void Start () {
		health = 0;
		while(health < 3) {
			health++;
			addHeart();
		}
	}

	void addHeart() {
		if(health <= 3) {
			if(health == 1) {
			}
			else if (health == 2) {
			}
			else if (health == 3) {
				GameObject heart3 = Instantiate(heart3p, new Vector3(transform.position.x + 2.12f, transform.position.y, 0), transform.rotation);
				heart3.transform.parent = transform;
			}	
		}
	}

	public void loseHeart() {
		
		if(health == 1) {
		}
		else if (health == 2) {
		}
		else if (health == 3) {
			Destroy(heart3); 
		}
	}
}

I’ve also tried:

else if (health == 3) {
   Destroy(GameObject.Find("heart3(Clone)"));
}

If someone could point me in the right direction that would be great. Searched google for an answer but nothing I’ve tried has worked.

Thanks

Hello there,

No worries, your script isn’t that far from being ready.

Here’s my version:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class healthControl : MonoBehaviour
{
    public int health = 0;
    public int maxHealth = 3;

    public GameObject heartPrefab = null; // Assign in inspector
    private List<GameObject> heartsList = new List<GameObject>();

    void Start()
    {
        health = 0;
        while (health < maxHealth)
        {
            health++;
            addHeart();
        }
    }

    void addHeart()
    {
        if (health <= maxHealth)
        {
            GameObject newHeart = Instantiate(heartPrefab, new Vector3(transform.position.x + 2.12f, transform.position.y, 0), transform.rotation);
            newHeart.transform.SetParent(transform);
            heartsList.Add(newHeart); // Add the heart to the list
        }
        else
            Debug.Log("Already at max health!");
    }

    public void loseHeart()
    {
        if (health > 0)
        {
            //Destroy the Gameobject and remove it from the list
            Destroy(heartsList[heartsList.Count - 1]);
            heartsList.Remove(heartsList[heartsList.Count - 1]);
        }
        else
            Debug.Log("Dead. Health is at 0.");
    }
}

I made it into a list, so now if you want to limit the max amount of hearts to something other than 3 you can just crank up the maxHealth variable.


I hope that helps!

Cheers,

~LegendBacon