Instantiating & Destroying GameObjects in Unity
A Simple Step by Step Tutorial
One essential skill you need is the ability to create and remove GameObjects while your game is running. In this step-by-step tutorial, we’ll learn how to spawn and destroy GameObjects in Unity, giving you the ability to spawn and remove objects, such as enemies, projectiles, powerups, etc. when certain conditions are met. Think of Super Mario Bros, when you jump and hit the ? box. The game spawns a coin that is immediately added to your total and then it is destroyed. Or the box spawns a mushroom that is destroyed when it collides with the player after providing the desired effect.
So how can we use this function in our own programs? And what does it look like in code? For this lesson, I’m going to make it so my player can fire lasers in a simple 2D shooter. Let’s jump right in!
Step 1: Setting up the Scene
- Open Unity and start a new 2D project
- In the Hierarchy Window, right-click, and choose 3D Object>cube. Name the cube “Player”.
- Again, in the Hierarchy Window, right-click, and select 3D Object>capsule. Name the capsule “laserPrefab”.
Step 2: Creating Scripts
- In the Project Window, right-click and go to Create>Folder. Name this folder Scripts. We can keep all the scripts for our game in this folder.
- Right-click the Scripts folder and select Create>C# Script. Name this Script PlayerBehavior and attach it to the Player GameObject. Repeat this for the LaserBehavior Script as well, attaching it to the laserPrefab.
- Double-click a script to open it in your code editor program. Let’s start with LaserBehavior to get it out of the way.
Be sure to attach your LasePrefab to the component in the inspector window within Unity.
4. Go back into Unity double-click the PlayerBehavior script. Or if the script is already in your code editor select the PlayerBehavior tab. (I have already given my player WSAD control. If you need assistance with this, check out my article Simple Player Movement in Unity 2D.)
Step 3: Edit Your Player Script
- Inside the PlayerBehavior script, let’s define the variables we need.
2. We’ll add code to handle object spawning using an If statement in the “Update” method:
Now when the Space key is pressed the program will run the FireLaser method.
3. This is a good time to add the FireLaser method. This is going to be the expression that instantiates our LaserPrefab.
Step 4: Testing the Instantiation Process
- Click the “Play” button to enter Play Mode.
- You should now be able to fire lasers by pressing the space key.
Summary
Now you know how to spawn and destroy GameObjects in Unity using the C# script. With enough experience, you’ll become a master at spawning and destroying GameObjects and leveling up your games! In my next article, I’m going to discuss Creating a Cooldown System.