Day 9: Instantiating & Destroying Gameobjects in Unity

Tyler Smallwood
3 min readMay 1, 2021

--

Fire!

Objective: Spawn an object and destroy it when it’s off the screen.

When we spawn an object we will use an system called instantiate. To use this we will need a game object that is a prefab. To start create a 3D object and move to project folder to make a prefab. In the project area, the name will turn blue to signify it’s a prefab.

Creating 3D capsule and making Prefab.

Now the code, first thing to do is get a reference to the prefab.

Reference to Prefab.

Now to check for input to instantiate the object and then instantiate the object.

Checking for Input and than Instantiating the object.

In the Instantiate, you need to pass in some data. The first will be the object to be created. The next is where it will be instantiated, so we use the player’s position(since this script is on the player). Lastly, we need the rotation, here we use the object’s original rotation.

Next will be to assign an object to the GameObject reference. Back in Unity, take the prefab you created, from the project window, and add to the player component on the Player object. Do not take a prefab from the hierarchy, because once it spawns the first time the object will disappear from the reference.

Adding the Game Object to the component

That will spawn the object, Now to delete the object.

We will need to create another script called Laser, for the laser’s behavior.

In that script we will need a reference for speed and use transform.Translate() to move the object up.

Moving the Laser up.

Now to destroy the object after it gets to high. We will check the y position of the object and if it’s greater than a specified position we will destroy.

Destroying an object.

That’s it! We have spawned an object into the game and forced it to move up until a certain position and then it gets destroyed.

--

--

Tyler Smallwood
Tyler Smallwood

Written by Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer

No responses yet