Instantiating and Destroying GameObjects in Unity

Pavel G Rodriguez Garcia
2 min readOct 15, 2022

So now that I have the cube (player) set up and moving about, next I am adding the shooting functionality to it. Its freaking lasers!!

https://unsplash.com/photos/SNfvyIoQ050

To get started with the lasers I created a capsule GameObject, shrunk it down to look a bit more like bullets. Once I had the look I was good with I next made the capsule laser/bullet into a prefab.

Making something into a prefab works better when creating many copies of said object. Next after creating a prefab of the laser/bullets I added functionality by creating a script, attaching it to the laser so that every time it is in the game, it will go “up”.

Once that was set up the next step was to make it so that once the space bar was pressed, the bullets/lasers were created and (because of the previous script) go up. This is the code for the shooting functionality implemented in the Update method.

With the basic movements of the player and the basic shooting functionality, the gameplay basics are coming together!

After getting the lasers to shoot, the next issue to resolve was the lasers themselves. Once instantiated they stick around! So to make the lasers go away after they go offscreen, I next put on the laser script this code to destroy the lasers.

--

--