The Life and Death of a GameObject

Soon into your project, you will realize that you need many of the same GameObject to achieve the look and feel you want for your game — be that enemies, weapon projectiles, birds in the sky or any other often used entity within your game.

Fortunately, we don’t need 100 enemy GameObjects made during design time. With Unity, we are able to create these GameObjects on the fly as and when we need them by using prefabs — or prefabricated GameObjects — and Instantiating instances of them.

Let’s use our Player’s laser for this example. First off, you need to create your laser. We’ll just use a Unity provided primitive capsule for now.

Name the capsule appropriately, zero out the position, scale it down to an appropriate size and position it just above our Player.

With this done, create a folder in your project window named ‘Prefabs’ and drag the Laser GameObject from the hierarchy into the new folder. You can then delete the Laser from the hierarchy.

Now we need to create the functionality to fire our Laser and call for our prefab to be created. In our Player script —

First, create a reference to our prefab — ensure you serialize this so it can be set in the inspector
Create the conditional check that fulfills our requirements for firing the Laser
Create an instance of our prefab

The Instantiate instruction has many ways to implement it, in this example, it uses 3 arguments — the GameObject we want to create an instance of, a Vector3 position for the newly created GameObject and a default rotation.

NOTE: For more information on the different ways to use the Instantiate method, check out the Unity docs — Unity — Scripting API: Object.Instantiate

Now we have the functionality for the laser implemented, save the script and head back to Unity. Select the Player and assign the prefab.

With a short script attached to our laser, we’re all set. And our Player creates as many instances of the laser as times you hit the spacebar or click the mouse.

This does lead to a bit of a messy hierarchy very quickly so we need to make sure that once our prefab is finished with and we no longer need it, we delete it from our game.

With a couple of lines added to the Laser script, we can dispose of the lasers once they pass a certain point.

And here ends the life of the GameObject, short and sweet, never to be seen again but maybe copied again and again and again and again…

A UK based Unity Developer with a passion for gaming and coding