Instantiating and Destroying GameObjects in Unity

Gert Coppens
3 min readMay 18, 2021

--

Let’s have a closer look at what we’ve been working with.

Instantiate()

In C# we have a method provided by Unity to make a copy (clone) of an object, similar as if you would copy and paste an object in the scene. This method is very powerful and we’ll be using it for projectiles, particle systems, explosion effects and in many other situations where we need to create a new object at runtime.

By default Instantiate() clones the object “original” and returns the clone. However there are a few optional parameters that we can declare.

The position and orientation for a new object, the parent that will be assigned to that new object and instantiateInWorldSpace to set its relative position in world space.

In our case the Instantiate() method makes a clone of a specified object “_laserPrefab”, its new position and its rotation.

Important to know is that if you are cloning a Component, the GameObject it is attached to is also cloned, including child objects and all other components with their respective properties.

Nota bene, none of these methods create a prefab connection to the new object, therefore we need to use another method called PrefabUtility.InstantiatePrefab which works very similar but keeps the prefab connection intact when cloning new objects.

You can find more information about instantiating objects in the Official Unity Documentation.

Destroy()

Unity provides us with another method that is inherited from the Object base class in order to remove a GameObject or Component.

Syntax

The object “obj” is destroyed immediately after the current Update loop and done before the rendering.

Example: Damage() Method in the Player script

For the Destroy() method we have one optional parameter, “float t;” which is the optional amount of time to delay before destroying the object.

Use Examples

For more information about destroying objects in Unity, you can visit the Official Unity Scripting API Docs.

In the next article, we’ll have a closer look at Physics in Unity.

Previous | Next

--

--