Instantiating & Destroying Gameobjects in Unity

Deon Jr.
2 min readMar 17, 2021

--

Day 3.

Now that the player can move it’s time to make them shoot! To do this we need to spawn a projectile from the player on a key press.

Our laser asset in Unity

First we make a gameobject to represent our projectile. For the prototyping stage we will use a capsule to represent this.

Spawning at origin
Spawning the projectile on keypress

This code above spawns our projectile but only at the coordinates of 0, 0, 0. Obviously we want them to spawn with the player so…

Spawning at player position
Passing arguments to spawn with player

Now we are getting somewhere! Lets make them move!

First a new script called Laser (shocking I know) added to the laser prefab.

transform.Translate command to make our projectile move in the vector3 direction of up.

And now..

We have shooting!

But… we still have a problem. nothing is destroying these gameobjects when they go off screen.

As you can see the y position keeps going because nothing is stopping it. Lets fix that.

We use the Destroy command when the object is off screen.

--

--