Instantiating & Destroying Game objects in Unity

Ameen Mohmand
3 min readJun 10, 2022

Objective: How to instantiate and destroy Game objects in Unity.

Were now gonna continue adding on to our Space Shooter Pro .For starters let’s make a game object that will be our laser in our Space Shooter Pro . The game object we will be using is a 3D object which will be a capsule for our laser. Next let’s position our capsule in the inspector by setting the scale on x, y, z axis to 0.2 . Also let’s reset the position on the x, y, z to zero too. The next thing let’s rename the capsule to laser in the Hierarchy or inspector.

In Unity were gonna create this laser game object at run time to start the game, so every time we hit the space key we fire off one these laser’s . This come’s down to reusable objects in Unity we call prefabs. So what are prefab’s to began with “I’ll tell you”, it’s a game object that can be instantiated at run time and hold references to each other. So for example were gonna prefab the laser by creating a Laser Prefab folder . In other words a prefab is just reusable object. Prefabs are basically share data across objects too. Next drag your laser from the hierarchy into the Prefabs folder. Once you dragged your laser into the prefab folder you will notice it turns blue. The reason it turn’s blue to signify its a prefab .

Next lets go ahead and make a material mat for our laser. First right click on your Materials folder and when the drop down menu appears scroll down to material and label your new material Laser_ mat. Next change the albedo color to your liking. Then simply drag your laser_mat material on to your laser in the hierarchy and then at the top in the inspector click on override and click apply all.

Now that we have our laser created lets talk about the behavior we want the player to have when we hit the space key and spawn the laser. We will break down how to instantiate game object in unity and how to incorporate it into our laser. Lets start by writing it out in pseudo code and then write in C#

Lets talk how to spawn game objects in Unity, you do it by creating new game objects with Instantiate. First lets make a GameObject laser Prefab in visual studios and make it private and use a serialize field attribute and it will show in the inspector and don’t forgot the underscore. Next drag the laser from the prefab folder to game object laser prefab on the script. Next instantiate the game object .

Now lets make a new C# script for our laser behavior and translate the laser up and give it a speed variable of 8 .

Now its time to destroy the laser.

--

--