Phillipv20 Phillipv20 - 4 months ago 15
C# Question

Destroying an object created by a script from within the script Unity3d C#

Ok guys and gals need a little help with this. Basically I'm instantiating a healthPack from a prefab in an open position. After a certain time elapses I am trying to destroy the HealthPack if it isn't picked up, set a bool healthPackExist back to false, and instantiate another healthPack at a free position.

When I've attempted to access the gameObject being instantiated I end up either destroying the whole Parent Hierarchy or just wiping the script out.

I've tried destroying the root object, searching for the name of the created object, adding a tag to the object (Health Pack) and searching for it always getting errors.

Code is below:

public GameObject healthPackPrefab;
public GameObject health;
private float healthTimer;
private bool healthExist;

// Use this for initialization
void Start ()
//set healthExist to false to indicate no health packs exist on game start
healthExist = false;

// Update is called once per frame
void Update ()
//first check to see if a health pack exist, if not call method to spawn a health pack
//otherwise check to see if one exist and if it does is it's timer created with it
//has been passed by Time.time (returns game clock time), if yes destroy the created
//health pack.
if (healthExist == false)
spawnUntilFull ();
else if (healthExist == true && Time.time > healthTimer)
//Error occuring here when trying to destroy
//Destroy(transform.root.gameObject) //destroys script, object scripts on, and prefab
Destroy(this.gameObject); //does same as Destroy(transform.root.gameObject
healthExist = false;

Transform NextFreePosition()
//free space
foreach (Transform childPositionGameObject in transform)
//if no health packs located return location of child object to spawn new health pack
if (childPositionGameObject.childCount == 0)
return childPositionGameObject;

return null;

void spawnUntilFull()
//returns next free position in space
Transform freePosition = NextFreePosition ();

//if free slot is available
if (freePosition && healthExist == false)
//instantiates health object and places it in scene at coordinates received from
health = Instantiate (healthPackPrefab, freePosition.position, Quaternion.identity) as GameObject;

//spawns enemy onto a position under the Parent (Enemy Formation)
health.transform.parent = freePosition;

//set bool to true to stop spawning
healthExist = true;

//seat HealthTimer to 5 seconds after creation for use in Update method
healthTimer = Time.time + 5.0f;


What you are effectively doing when you call Destroy() is destroying the script. To achieve what you want (destroying the health pack) you simply have to call Destroy on it instead:


On a side note, to avoid messy code using Time.time, Destroy() has an overload that uses two parameters:

Destroy(GameObject object, float delay);

This should help simplify your code and make it more readable.