Utilizing Tags for GameObject Categorization
In this lesson, you will learn how to use Tags to categorize your GameObjects so your scripts can easily find and identify them during gameplay.
What are Tags?
Think of a Tag as a "label" or "category" you stick onto a GameObject. While a name distinguishes an object from another (like "Enemy_Orc_01"), a tag groups many objects together (like "Enemy"). This is incredibly useful when you want your game logic to perform an action on a group, such as having a player's sword detect if it hit an "Enemy" or a "Coin."
Applying a Tag
To tag an object:
- Select the GameObject in your Hierarchy.
- In the Inspector window, look at the very top, just below the object’s name.
- Click the Tag dropdown menu.
- Select an existing tag (like "Player" or "Respawn") or click Add Tag... to create a custom one of your own.
Identifying Tags in Scripts
Once you have tagged your objects, you can check for those labels inside your C# scripts. This allows you to write logic that says, "If I bump into something, is it a Coin?"
You can check an object's tag using the CompareTag() method:
void OnCollisionEnter(Collision collision)
{
// Check if the object we hit has the "Coin" tag
if (collision.gameObject.CompareTag("Coin"))
{
Debug.Log("You picked up a coin!");
}
}
Why use CompareTag?
You might notice you can access gameObject.tag directly, but using CompareTag() is the industry standard. It is faster for the computer to process and helps prevent errors, making your code more robust as your game grows. By using tags, you avoid hard-coding specific names, meaning you can easily swap out models or add new enemies without having to rewrite your underlying logic.
Key Takeaway: Tags provide a simple, efficient way to label and group your GameObjects, allowing your scripts to perform logic based on category rather than specific identity.