Spawning and Destroying Objects in Unity

Matthew Givens
2 min readApr 20, 2021

--

With the rough outline of a 2D shooter game complete, the next step is creating the ability for our player to fire lasers. In Unity the lasers we shoot will be prefabricated game objects. Prefabs allow us to easily make new copies of a game object that will inherit modifications to the original. We will add textures for our game objects later, but for now create a new 3D cube named “laser”.

Next, create a folder under Assets called Prefabs to make our laser a prefab and keep the project organized. From the hierarchy drag “laser” to the prefab folder.

In order to spawn the lasers we will utilize the instantiate function in our player script using the space key. To make things look a little cleaner, instantiate the laser a short distance in front of the player.

Now the lasers spawn on our player with the space key but they remain stationary. Let’s fix that with a new “laser” script. Create a variable to store the laser speed and serialize it to make easily make modifications in the future.

Put the laser in motion by accessing the translate component. We want an upward direction multiplying the speed variable by delta time to remove frame rate dependency.

With that we are almost finished, but leaving the laser clones in our game traveling infinitely is a problem. Ideally, the lasers should be destroyed once out of view. Write a conditional statement using the y position just out of frame. Using the destroy function will solve this problem.

--

--

Matthew Givens

A self-taught Unity developer, learning more everyday and documenting my journey. My passion for the world of game development grows with every skill I pick up.