In this lesson, you will learn how to use Tags to label your GameObjects and locate them instantly in your code using GameObject.FindWithTag.
What are Tags?
Think of Tags as simple labels or categories for your objects. Just as you might categorize folders on your computer, Tags allow you to group objects like "Player," "Enemy," or "Collectible" so that your scripts can quickly identify which objects are which during runtime.
To assign a tag, select any GameObject in your Hierarchy. In the Inspector window, click the Tag dropdown menu (right below the object’s name). You can choose an existing tag or create a new one by clicking "Add Tag..."
Finding Objects with Code
Once an object is tagged, you don't need to manually drag and drop it into a script's slot. Instead, you can search for it dynamically. This is useful when you have multiple objects of the same category, or when you are spawning objects during gameplay.
Here is how you search for an object using GameObject.FindWithTag:
using UnityEngine;
public class TagSearcher : MonoBehaviour
{
void Start()
{
// This searches the entire scene for one object with the "Player" tag
GameObject player = GameObject.FindWithTag("Player");
if (player != null)
{
Debug.Log("Found the player: " + player.name);
}
else
{
Debug.LogWarning("No object with the tag 'Player' was found!");
}
}
}
Why use this instead of direct references?
While caching references with GetComponent is faster for performance, tagging is incredibly flexible. If your game level features a "Boss" that spawns only after a certain event, you don't need to link it in the editor beforehand. Your script can simply search for the "Boss" tag the moment the enemy appears in the scene.
Remember: GameObject.FindWithTag returns the first object it finds with that tag. If you need to find every object with a specific tag (like every "Coin" in the scene), you would use GameObject.FindGameObjectsWithTag, which returns an array of all matches.
Key Takeaway: Tags provide a flexible, label-based system to dynamically locate objects in your hierarchy at runtime without needing manual Inspector assignments.