How to Instantiate and Destroy a GameObject in Unity - Owlcation - Education
Updated date:

How to Instantiate and Destroy a GameObject in Unity

Author:

Creating and removing GameObjects in Unity happens all the time in just about every game, and so one of the first things a beginner programmer needs to learn is how to both Instantiate and Destroy GameObjects. The one process ties into the other, so we're going to approach this topic from the opposite end and look at Destroying a GameObject first.

Destroying a GameObject

Destroying a GameObject in Unity requires, at its most basic, only two elements:

  • A script that derives from MonoBehaviour, Unity's standard base class for virtually everything the program does; and
  • A single line of code: 'Destroy(insertGameObjectHere);'.

Assuming you have those two elements in play in a script you can destroy a GameObject. Sounds pretty easy, right? Here's a quick example:

how-to-destroy-a-gameobject-in-unity

In this case you have a GameObject, stored as 'guyGameObject', and a Destroy command that triggers if you hit the F key. You also have a script derived from MonoBehaviour, as Destroy won't be recognized as a function outside of this all-important base script. This will, in theory, remove the GameObject and everything childed to it from your game when you hit F. Pretty easy.

... except, despite the code being technically correct, this won't actually work. Instead you'll get a small error in the Console at the bottom of the screen: 'Destroying assets is not permitted to prevent data loss.' What does this mean? To explain, we'll need to look at Instances.

Creating an Instance of a GameObject

Instances are clones of prefabricated GameObjects - prefabs - which form the basis of all in-game interactions in Unity. A prefab is created whenever you drag a GameObject from the Scene view into the Project view, thereby saving it in your game's Assets. The prefab can then be drawn upon via Inspector variables to create copies for runtime purposes. Think of the prefab as a blueprint for an object, and the Instances are the manufactured result of that blueprint. You don't want to use and discard the blueprint, just the manufactured results.

As a consequence of this, Unity will display the aforementioned error whenever you (accidentally) try to Destroy a prefab. If you see the error you know that you're trying to Destroy the wrong thing. So in order to fully understand how to Destroy a GameObject in Unity, you also need to understand how to Instantiate an object.

Create a new script (or use one already in progress) and add a new public GameObject variable, as above. Then go back to the Inspector and add a prefab to your script, like so:

how-to-destroy-a-gameobject-in-unity

You now have a connection to the prefab blueprint in your script. Using the guyGameObject variable you can create an Instance of the prefab using this line of code:

Instantiate(guyGameObject);

When this script is run, assuming guyGameObject is assigned to a prefab, a clone of that GameObject will be created in your game, appearing at the same coordinates contained within the prefab. You can even assign new coordinates, if you like, and change where the clone of guyGameObject will appear:

Instantiate(guyGameObject, new Vector3(0, 0, 0), Quaternion.identity);

This will create a clone of guyGameObject at the global coordinates of 0, 0, and 0. You can also use the Vector3 of another object to Instantiate your clone in a movable spot by creating another variable and assigning it to an active GameObject like so:

float instX = instantiateObjectHere.transform.position.x;
float instY = instantiateObjectHere.transform.position.y;
Instantiate(guyGameObject, new Vector3(instX, instY, 0), Quaternion.identity);

This code grabs the x and y coordinates of the new GameObject, plugs them into the Instantiation code, and creates a clone at those same coordinates. This form of Instantiation can be very handy for creating enemy spawn points or weapons that fire projectiles from a single spot.

Combining Instantiate and Destroy

Ready to Destroy your creations? There's one more step before you can do so via script: Add the Instantiated objects to another GameObject variable. In this case we'll use a local variable to do the job:

GameObject objectToDestroy = Instantiate(guyGameObject, new Vector3(instX, instY, 0), Quaternion.identity);
Destroy(objectToDestroy);

Typically you would not create and then immediately Destroy a GameObject, particularly not in the same function, but the point here is clear: Declare the new Instance as objectToDestroy, then Destroy that GameObject. No more Instance, and no error to boot since it is an Instance and not a prefab.

A full example of a script that could create and Destroy Instances might look something like this:

how-to-destroy-a-gameobject-in-unity

Press G and an Instance of guyGameObject is created at the coordinates of instantiateObjectHere. Press F and that new GameObject, now defined as newInstance, is Destroyed. That about does it!

This is, of course, not the only way you can implement either Instantiate or Destroy in your games. Objects can be created and destroyed when:

  • A GameObject strikes the Collider of another GameObject;
  • A timer reaches a certain count;
  • A boolean is triggered;
  • A GameObject reaches a certain speed; and
  • Plenty others. There are probably hundreds of small, specific scenarios which could trigger the creation or destruction of an Instance.

One Final Note!

It is worth knowing that there's one other way to create an Instance of a GameObject, and that's to drag a prefab into the Game view from your Assets. This is often done to design pre-determined situations into a game: for example, if you knew you wanted an enemy to appear at a specific spot on a map, you would drop it into the game. This would count as an Instance and could be destroyed without an error. This is also how you would create spawn points in the first place, so there is a lot of mixing-and-matching of the two methods of Instantiation that you'll wind up using in just about any Unity game.

Related Articles