Tags and layers help you organize and identify objects in your game easily. They let you group objects for interaction, collision, or special effects.
0
0
Tags and layers in Unity
Introduction
When you want to detect if the player touched an enemy or a collectible.
When you want to make certain objects ignore collisions with others.
When you want to apply effects only to specific groups of objects.
When you want to find or filter objects quickly in your scripts.
When you want to control rendering or physics behavior by grouping objects.
Syntax
Unity
gameObject.tag = "TagName"; int layer = gameObject.layer; gameObject.layer = LayerMask.NameToLayer("LayerName");
Tags are strings you assign to objects to identify them.
Layers are numbers used mainly for collision and rendering rules.
Examples
Check if the object has the tag "Enemy" before acting.
Unity
if (gameObject.tag == "Enemy") { // Do something }
Assign the tag "Collectible" to this object.
Unity
gameObject.tag = "Collectible";Set the object's layer to "Ignore Raycast" so it won't be detected by raycasts.
Unity
gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");Sample Program
This script sets the object's tag to "Player" and layer to "Default". Then it checks the tag and prints both tag and layer to the console.
Unity
using UnityEngine; public class TagLayerExample : MonoBehaviour { void Start() { // Assign tag and layer gameObject.tag = "Player"; gameObject.layer = LayerMask.NameToLayer("Default"); // Check tag if (gameObject.tag == "Player") { Debug.Log($"This object is tagged as: {gameObject.tag}"); } // Show layer number Debug.Log($"This object is on layer: {gameObject.layer}"); } }
OutputSuccess
Important Notes
Tags must be created first in Unity's Tag Manager before assigning.
Layers are limited to 32 slots; use them wisely for collision and rendering rules.
Use tags for identification and layers for physics or rendering control.
Summary
Tags help identify objects by name.
Layers help group objects for collisions and rendering.
Use tags and layers together to organize your game objects effectively.