Objects are giveth, and then taketh away…

Instantiating and destroying objects in Unity

Christopher West
2 min readApr 1, 2021

While developing our games we need a way to bring objects into our play space so that the user can see, and possibly interact with, them. To do this we use the Instantiate method that Unity provides us. The signature looks like:

This method creates an instance of the objects requested at the position and rotation supplied and, optionally, within the parent container in the scene hierarchy. We use Quarternian.identity to tell the function to use the objects rotation as defined when the object was defined.

One we have the object in the scene we can modify it as necessary for its game behavior. Using its visibility, position, and other properties to have it interact with the player and/or the game world. We use this technique in our space shooter project to spawn lasers for our players and enemies for the player to shoot them at, among other things.

Now that we have objects in our scene there are certain to be situations in our game where we want to remove those objects! Situations like removing a later once it has hit an enemy and removing the enemy itself both fall under this umbrella. Luckily, Unity provides a function for that too! We can use the Destroy function, whose usage looks like:

As you can see this function takes two parameters. First, it takes the objects you want to destroy and, as an optional second parameter, you can specify the amount of time to wait before the object is destroyed. We use this to remove our leaders and other game objects upon collisions (a topic for a future article, and when the lasers go out of the screens bounds. Removing the lasers once they are past the bounds of the play space helps keep our scene hierarchy cleaner and helps keep our games memory footprint down.

Next time!

Today we took a look at how we can get objects like weapons fire and enemies into our game and hire to remove them when they are no longer needed. If you enjoyed this article, or want to come along with me as I progress on my journey, follow me at gamedevchris.medium.com.

--

--

Christopher West

Unity Game Developer, Software Engineer, Gamer, Musician, and Father. Christopher is a creative that enjoys a challenge and loves coding.