Instantiate & Destroy a Game Object- Game Dev Series 06
Previous: You Should Use Pseudo Code
As a shooting game, the second basic function of our player is shooting. We need to create bullets when press the specific key. Then we need
Instantiate to spawn a bullet.
First, let’s make a bullet.
Create a capsule and named it Laser, then scale it to 0.2 on X, Y, and Z.
As a bullet, we want it to go up when we shoot it. To do that, create a C# script called Laser and attach to the Laser game object.
Then add the force up inside
Update() as we did to our Player in the previous articles.
Then we need to create a Prefab. A prefab is a stored game object which can be copied without losing any setting. We use prefab to generate laser to make sure every laser has the same value.
Create a folder called Prefabs in the
Project window, and drag the Laser game object from
Hierarchy to this folder.
You will notice the Laser in
Hierarchy turns to blue which means it became a prefab. Since we have already created a prefab, we can delete the one in the
It’s time to instantiate it!
Let’s say I want to shoot the laser when pressed “space” key. We need to create an if-statement to do this part.
And we also need to tell our script what should be our laser when shooting. To do this, we should create a private but adjustable variable for our laser prefab,
Back to Unity and drag the Laser prefab to the component in the
Now our script should know what is laser that we want to generate.
Let’s create our shooting method under out movement function.
Instantiate(_laserPrefab, transform.position, Quaternion.identity);
Here are some key points about this statement:
- For if-statement, it works when we press the space key down
- The first part inside the
Instantiateis our prefab which we want to generate.
- The second part is the position when generate, which is as same as our player.
- The third part is rotation when generate, and we use
Quaternion.identitymeans stay as default in this situation.
Let’s play it and see how is the result,
Now we create tons of laser bullet but the bullets won’t disappear after we shot it.
Destroy to destroy a game object.
We need to find out when should our bullets got destroyed. Drag our Laser prefab into
Hierarchy and move it on the Y-axis,
You can see the bullet out of game screen at about 7.5 on Y-axis, let’s make it disappear when it reach 8.
Open the Laser script and add an if-statement in the
if(transform.position.y > 8f)
Destroy needs to contain a game object which we use
this.gameObject to assign the game object where this script attached.
Let’s Play it again and check the result,
Next: A Cooldown System