- Home /
 
               Question by 
               alexander11 · Sep 24, 2016 at 12:03 AM · 
                c#unity 5instantiate3ddestroy  
              
 
              Removing instantiated objects??
Hello how do i make it where i instantiate an object but when i instantiate another object it deletes the previous one, does anyone know how to do this(in C#)??
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by Hanoble · Sep 24, 2016 at 12:54 AM
You would need a reference to the previous object, and then do a Destroy() with the previous object. An example might be something like:
 private GameObject currentInstantiatedObject;
 
 void Spawn()
 {
     //Destroy the previous object if there is one
     if(currentInstantiatedObject != null)
         Destroy(currentInstantiatedObject)
 
     //Instantiate the object
     GameObject spawnedObject = Instantiate(prefab, spawnPosition, Quaternion.identity) as GameObject;
 
     //Set the current object to this spawned object, so it can be destroyed     next spawn.
     currentInstantiatedObject = spawnedObject;
 }
I believe it should say
 private GameObject currentInstantiatedObject;
ins$$anonymous$$d of just
 private currentInstanctiatedObject;
You are correct. Was simply an error on my part to forget the GameObject, will edit, thanks for having my back!
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                