AZSWQ
AZSWQ

Reputation: 319

Unity - Whats the Opposite of instantiate - Transform not destroying

I an trying to destroy prefab1 below ( destroying its game object) in update but the prefabs do not get removed in my game. DESTROYING HOLE 1 GEMS debug below appears in console and gameobject is destroyed but the gems (prefab sprite) do not get removed from my game even when gemCount_Hole1 is less than 1 . Please help

            if (gemCount_Hole1 < 1)
        {
            Debug.Log("DESTROYING HOLE 1 GEMS");
            if (prefab != null) Destroy(prefab.gameObject);
        }
        else
        {
            for (int i = 0; i < gemCount_Hole1; i++)
            {
                Instantiate(prefab, new Vector3((i + xPos_Hole1) * 2.0F, -14, 0), Quaternion.identity);
            }
        }

I created a list but dont know how to write the destroy. Here is how I coded it as a list

 private System.Collections.Generic.List<GameObject> list ; 
 void Start()
 {
  list  = new System.Collections.Generic.List<GameObject>();
 } 
 void Update()
 {
  for (int i = 0; i < gemCount_Hole1; i++)
  {
   list .Add( Instantiate(prefab, new Vector3((i + xPos_Hole1) * 2.0F, -14, 0), Quaternion.identity)) ;
  }
 }

Upvotes: 1

Views: 3421

Answers (1)

byIcee
byIcee

Reputation: 145

You can't destroy a Prefab directly.
When you instantiate the prefabs as GameObjects, you have to store them into an Array GameObject[] or List then, when destroying it, finding it in the list and destroy it from there.

Upvotes: 2

Related Questions