Javatpoint Logo
Javatpoint Logo

Unity GameObject Destruction

Like instantiation, the destruction of GameObjects is also important. In this section, we will understand how to destroy the GameObjects.

Destroying a GameObject is very simple as creating a GameObject. You require a reference to the object to be destroyed, and call the Destroy() method with this reference as a parameter.

Let's create 5 diamonds, which destroy themselves when an assigned key is pressed.

First of all, create a new script. Rename it to Destroyer.cs and open it on an editor. Now, copy the following code:

Here, we used a public variable for KeyCode. A KeyCode is used to describe a key on a standard keyboard, and the input class in its method uses it. By making this variable public, we can make it accessible through the editor. When the variable is made public, we don't need hardcode values such as KeyCode.A into the code.

Here, we have added the gameObject variable. This new gameObject variable is used to refer to the gameObject this script is attached to. If you add this script on multiple objects, they will all react the same way whenever this variable is involved.

Now, we will create a new diamond sprite and attach our script (Destructor.cs) to it. Next, right-click on the gameObject from the hierarchy tab and select the Duplicate option. A new sprite is produced in the hierarchy tab; you should use the Move tool to reposition it. Repeat the steps to create similar diamonds.

Unity GameObject Destruction
Unity GameObject Destruction

Click on each of the diamonds and look at their script components. You can now set the individual keys in the 'key to destroy' option so that a GameObject destroys itself when that key is pressed. For example, let us create 6 diamonds, and set them to destroy when the A, S, D, F, G, and H keys are pressed.

Unity GameObject Destruction
Unity GameObject Destruction

The same key can be set on multiple diamonds, and they will all destroy themselves simultaneously when the key is pressed; this is an example of the use of the gameObject reference, which you can use to refer particular objects using the script without having to set them individually.

It is vital to understand that destroying a GameObject does not mean an object will explode or shatter. Destroying an object will simply cease its existence as far as the game (and its code) is concerned. The links to this GameObject and its references are now broken, and trying to access or use either of them will usually result in errors and crashes.

Unity GameObject Destruction
Next TopicUnity Console




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA