Understanding “Tag” in “Unity”

Definition: Tag is basically grouping the different types of game object by assigning them with a name.

For example, let us consider that there are 2 types of enemies such as “square” and “circle”. When the player collided with any of those enemy, the player will die. So far that I have taught you guys, you might be thinking to type your codes like this,

void OnCollisionEnter(Collision other) {

if(other.gameObject.name == “square” || other.gameObject.name == “circle”){

Destroy(gameObject);

}

}

But what if, there are 20 types of enemy in your game, so are you going to type their every single name to your code? And what if there are 20 “circle” enemy in the game, where their naming comes to “circle (1), circle (2) …..” by copying in unity. So are you going to type all of their name through your code? Definitely not, this is where the tagging comes. We are going to create an “Enemy” tag from the “Tag” window in “Unity” and set that “Enemy” tag to our different type of “Enemy” game object. Let’s see how we can create and use tags on unity on the following steps.

 

  1. To create those tag, lets select a “Game Object”.

Tag (1)

  1. Here, as we selected “Enemy (6)” from the “Hierarchy”. As now we can see that the “Tag” is now set with “Untagged” means, that there is no tag for the following “Game Object”. Let’s click on the drop down menu of the “Tag”.

Tag (2)

Now “Click” on the “Add Tag…” section to creating a “tag” for the following “Game Object”.

  1. Now you can see that the following “Inspector View” has changed to “Tags & Layer” section.

Tag (3)

As we don’t have any “Tags” right now, so the following list is showing “List is Empty”. Let’s click on the small “+” (Add) sign icon to create our first tag.

 

  1. Let’s set our new tag name as “Enemy”, and click on the “Save” button.

Tag (4)

  1. Now we can see that the “Enemy” tag is now available on the “Tags” list.

Tag (5)

  1. Again, let’s select the “Enemy (6) from the “Hierarchy” and click on the dropdown menu of “Tags” to select the “Enemy” tag for our enemies.

Tag (6)

  1. After selecting the “Enemy” tag, it is now been displayed on the “Tag” section of the “Inspector View”.

Tag (7)

  1. As now we have set the enemies with the “Enemy” tag, we can write our code in something like this,

void OnCollisionEnter(Collision other) {  if(other.gameObject.tag == “Enemy”){         Destroy(gameObject);    }}

Where this script will now destroy the player (assuming this script is attached to “Player”) as it touches with any object containing “Enemy” tag.

 


# The reference of the documents are taken from the “Unity – Documentation”.

Muhammad Tashfiqul Bari

Mentor at Coursera

 

 

Author Muhammad Tashfiqul Bari

More posts by Muhammad Tashfiqul Bari

Leave a Reply