Unity Fundamentals — Instantiating & Destroying

With the power to create you also get the responsibility of taking away, these are simple functions to use but can be difficult to master.

Let us take a moment to get acquainted with the use of these functions since we will be using them a lot while working in Unity.

Instantiating Gameobjects

When developing games you need a way to bring objects into existence. In Unity we use the Instantiate function to do just that.

When we Instantiate an object we need a few parameters make this work.

Object — First up we have the object we want to instantiate here we use the variable (prefab).

Position — Next, we need to tell it the position where to create the object. here we use a new Vector 3 to define this location but you could also use other position data here like a transform.position or another variable as long as it returns a vector3.

Rotation —Now we define the rotation of the object we are bringing to life, we use Quaternion.identity here, that means the rotation the object had when the prefab was created.

Parent — You can also define a parent the object will be nested in, but we will go deeper into this in the next article where we focus on cleaning up the clutter.

Destroying

Now that we have a way to create objects we also need a way to destroy them.

The object obj is destroyed immediately after the current Update loop, or t seconds from now if a time is specified. If obj is a Component, this method removes the component from the GameObject and destroys it. If obj is a GameObject, it destroys the GameObject, all its components and all transform children of the GameObject. Actual object destruction is always delayed until after the current Update loop, but is always done before rendering.

source: https://docs.unity3d.com/ScriptReference/Object.Destroy.html

The destroy function is pretty straightforward and only takes 2 parameters.

Object — We can define what object we destroy, it can be the current object, a component or another object stored in a variable, for instance in the case of a collision we can destroy the game object we collided with (but more on that later)

Time — We can also set a delay timer, this can be very useful if you are playing an animation hen would destroy the object because when you destroy the object all animations or other components are destroyed with it and don't have a chance to play or be executed.

Today it was a short one but don't underestimate the importance of these functions. They are at the heart of every program and while simple they can be used in a lot of awesome ways which we will explore throughout the course of our journey.

Thank you for your time and I appreciate you taking the time to read this article!

Have a great day and happy coding!