Instantiating & Destroying Game Objects in Unity

Christopher Pearl
2 min readJun 17, 2021

What is Instantiation?

While building the prototype for my spaceship shooter game, I needed to create lasers that would collider into the enemy ships attempting to attack my player ship. To have more than one laser fire from my ship, I needed to create multiple instances of a laser that would be created whenever I press the space bar. This was a good time to use the Instantiate() function.

What is Instantiate()?

Instantiate is creating a copy of an object. In this case, I used Instantiate to spawn the laser gameobject at a certain point above the shooter to add a smooth natural look (you’ll see later when art assets replace these crude models). In order to Instantiate and object, first create it as a Prefab in your projects folder.

I applied the function to the laser Prefab created, used transform.position to find the current location of the laser gameobject. Then I used new Vector3 to go inside the transform of the laser in Unity and relocate the laser on the Y-axis, and finish with Quaternion.identity because there was no rotation needed for this game object (this makes the rotation neutral).

Too many Copies!

While creating copies and getting my shooter to fire laser was accomplished, I didn’t want my Hierarchy filled with hundreds of copies of my laser object. I needed it to serve its purpose of going up toward the enemy ships, and the disappearing from the game. To do this, I needed the Destroy() function to my Laser script.

By adding the Destroy() function in my method, it allowed the lasers to be created and fired within the game after the position was checked as a condition, and removed immediately out of the game if it reached the position of moving off the screen (in this case, 8.0 floating point which is right after it disappears from the top of the screen). Using this.gameObject within Destroy() allowed me to get rid of the object this script was attached to, the laser itself.

Now we’ll be clearing these enemies right out of space!

--

--

Christopher Pearl

Unity Developer, AR/VR Developer, Virtual Reality Product Manager for Micro Medical Devices Inc.