Instantiate & Destroy

Creation and Destruction of objects

Instantiate is a Unity script terminology that spawns an cloned object. A quick understanding of how this is applied in gaming are “bullets”. Bullets in games are “Instantiated” objects that spawn from the gun, every bullet being shot is a clone.

Before we can begin, we first must make a “prefab” of a game object. A prefab is basically a Original object that is ready to be clone in the masses. It also allows quick changes and edits. If you have multiple game objects such as trees and you edited one and want to applied to all, with prefabs you can. Create a new folder to contain prefabs and name it “prefab”. Creating a prefab is very easy, just click and drag whatever game object on the Hierarchy into the newly created prefab folders. The name of the game object would turn blue indicating that it was successfully converted into a prefab.

To use the instantiate script, according to the Unity scripting API the following must be written.

Instantiate (prefab, transform.position, Quaternion.identity);

An example script of “when the space key is pushed down” a laser prefab shall be spawned at the same position of the player without any rotations.

“Quaternion.identity” is how Unity handles the identifications of rotations, by having this script at the end means that once this prefab object is spawn, it shall have no rotation.

Now that we are able to spawn infinite game objects, you might have noticed that the objects stay on the field. This doesn’t make sense especially from a optimization perspective since each game object is taking precious space. Therefore, we must destroy it.

The scripting API for destroy is rather simple, it is “Destroy();” Typing this method on any script would destroy this instantly. Since we don’t want that, we can have a limiter attached to it.

Using an “if” command, we can set a minimum distance before we invoke the destroy command. Since we only want to destroy this one game object (aka. bullet) we type “Destroy(gameObject);” to destroy this game object.

A Designer, an Illustrator and a massive tech geek aspiring to become a professional Unity Developer.