2D Unity Game Dev — Day 2 — Spawning and Destroying Prefabs GameObjects in Unity.

Michel Besnard
6 min readMay 10, 2021

--

Objective: Instantiate a “projectile” GameObject fired from a movable cube and destroying the projectile once it departs the game view. This builds on my previous article found at:

https://myjl-besnard.medium.com/take-control-and-move-that-cube-7b8cebaf8a26

Part 1 — Creating our Laser Prefab GameObject

Let’s begin by creating a new 3D GameObject, using a Capsule. Reset its Transform Position to (0,0,0), and reduce its Scale down to (0.2, 0.2, 0.2).

In your Project window (if not already done so) create a few extra folders to help organize our project. Call them: Scripts, Materials, and Prefabs. Let’s now rename the Capsule GameObject we created above to Laser, and drag it into the Prefabs folder.

In the Materials folder, create a new material, rename it Laser_mat, set the Albedo channel to your desired color (in my case, I’ve made it red), then drag this new material into the Inspector window with your Laser Prefab selected.

Congratulations! You’ve just created a reusable object (Laser Prefab) which we’ll be able to instantiate (or recreate) at will. Let’s now move on to scripting this feature in order to allow our Player to “shoot” these lasers on command.

Part 2 — Fire them lasers!!!

Now that we have this cool prefab, we need to figure out how to make it appear on your screen, preferably on command following a keystroke. In our example, we will use the Space key to fire our laser. Making this prefab’d GameObject instantiate is the process of spawning or creating a clone of the prefab into your game. This action is initiated by the main Player, therefore the required code will need to be part of the Player script. Since we wish to detect with high fidelity the firing of a weapon, it makes sense to incorporate the code in the Update() function.

Before we can do this, we need to create a serialized private variable of type GameObject, and we’ll call it _playerLaserPrefab. We then want to select and drag the Laser prefab into the Player’s _playerLaserPrefab gameObject field.

Our next step will be to detect the Space key in the Update() function using the Input.GetKeyDown and looking for the KeyCode named Space. When the Space key is pressed, we will then Instantiate the GameObject stored in the _playerLaserPrefab at the same location as our Player. We do this by reading the Player’s transform.position and offsetting the spawn point slightly on the Y-axis in order to avoid the Laser appearing clipped as it departs the Player. This is done by adding a new Vector3 to the transform.position of value (0, 0.7f, 0).

Quaternions are used to represent rotation. In our case, we do not want to induce any rotation in the instantiated GameObject, therefore we used the Static Property ‘identity’ to remove all rotation.

Save this script and run the game. Every time you press the Space key, a Laser GameObject will be spawned (instantiated) at the location of the Player. In the next step, we will create behavior and attach it to the Laser prefab to move the laser up until it departs the game screen.

Lasers being instantiated as the Player moves around and presses the Space key.

Part 3 — Up, Up, and Away!

The initial joy we feel as our laser shots get instantiated on the screen turns to confusion and dismay as we watch them just sitting there. So what’s missing? Now that we’ve managed to spawn them, we need to write a script which will give them a behavior, which in our case is that we want these laser shots to move in a direction away from the Player GameObject.

When I first tried to do this, I didn’t quite get the concept that the behavior should be attached to the prefab, and I thought it needed to be coded next to the snippet which instantiated the Laser prefab. I came to realize that it made more sense to write a script specific to the desired behavior and attach it directly to the Laser prefab. 💡

Here’s what you do: create a new Script, rename it Laser, and with the Laser prefab selected, attach the Laser Script to the prefab by dragging it into the Hierarchy or onto the prefab itself in the Project window.

Open your script in your editor (I’m using MS Visual Studio). Let’s add a private variable of type float to set the speed of the Laser, and Serialize the Field in order to make changes in the Hierarchy.

Then, in the Update() method, starting with a bit of pseudocode do guide our thoughts, we want to move, or translate, the GameObject up. We do this by taking the objects transform.Translate, moving it up multiplied by the speed of the laser (which was set above), and finally multiplying it by Time.deltaTime to move the object in real time.

The last part of our code needs to deal with cleaning up all those pesky laser prefab Laser Clones which left the screen. Do you see how they just stick around in the Hierarchy above? There are a few methods we could use, but the easiest I found basically entails running an IF statement which checks the current position of the GameObject along its Y-axis. In our case, if the Laser’s Y-position is greater than 8.0f, then it’s off the screen and can be safely destroyed. So in our case, once the laser reaches 8.0f, it will be destroyed.

This is starting to look pretty cool 😎. The enemy hordes won’t have a chance! Unless of course we make a few changes to level out the playing field somewhat 🤔.

In our next article, we’ll look at implementing some sort of method to control or limit the Player’s rate of fire. See you then!

--

--

Michel Besnard

Military member with 35+ years of service, undertaking an apprenticeship with GameDevHQ with the objective of developing solid software engineering skills.