What is Tag in Unity: Simple Explanation and Usage
tag is a label you assign to a GameObject to identify and group it easily. Tags help you find, filter, or interact with objects in your game through code or the editor.How It Works
Think of a tag in Unity like a name tag at a party. It helps you quickly spot who someone is or what group they belong to without asking every detail. In Unity, you attach a tag to a GameObject to mark it with a simple identifier.
This makes it easy to find or manage objects in your game. For example, if you tag all enemies with "Enemy", you can quickly find all enemies in your scene or check if a player collided with an enemy by checking the tag.
Tags are strings chosen from a list you create in Unity's editor. You can assign one tag per GameObject, and then use Unity's built-in functions like CompareTag or FindGameObjectsWithTag to work with those objects in your scripts.
Example
This example shows how to check if a player touched an object tagged as "Enemy" and print a message.
using UnityEngine; public class PlayerCollision : MonoBehaviour { private void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("Enemy")) { Debug.Log("Player hit an enemy!"); } } }
When to Use
Use tags when you want to group or identify objects without creating complex references. For example:
- Detecting collisions with specific groups like enemies, pickups, or hazards.
- Finding all objects of a certain type in the scene, like all checkpoints or spawn points.
- Organizing objects logically in your game to simplify code and improve readability.
Tags are best for simple categorization. For more detailed data, consider using components or layers.
Key Points
- Tags are simple text labels assigned to GameObjects.
- Each GameObject can have only one tag.
- Tags help find and identify objects easily in code.
- Use
CompareTagfor efficient tag checks. - Tags are created and managed in Unity's Tag Manager.