Lesson 87 +10 XP

Tags and Layers

Tags and Layers

Tags and Layers are two mechanisms Unity provides for categorising GameObjects. They serve different purposes and are used in different contexts.

Tags

A Tag is a text label you assign to a single GameObject. Tags are primarily used in scripting to find or identify GameObjects at runtime.

Assigning a tag in the Inspector: Select a GameObject, then use the Tag dropdown at the top of the Inspector to pick an existing tag or add a new one.

Finding GameObjects by tag in code:

// Find the first active GameObject with this tag
GameObject player = GameObject.FindWithTag("Player");

// Find ALL active GameObjects with this tag
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");

Comparing tags: Avoid using gameObject.tag == "Player" directly (creates garbage). Prefer:

if (other.CompareTag("Player"))
{
    // More efficient, no string allocation
}

Layers

Layers are integer indices (0-31) assigned to GameObjects. Unlike tags, layers are used by engine systems like physics and rendering, not just scripts.

Key uses of Layers:

  • Physics Layer Collision Matrix: Define which layers can collide with which (Project Settings > Physics).
  • Camera Culling Masks: A Camera only renders GameObjects on layers included in its Culling Mask.
  • Raycasts with LayerMask: Target specific layers during raycasts.

Raycasting with LayerMask:

// Only detect hits on "Ground" and "Obstacle" layers
LayerMask mask = LayerMask.GetMask("Ground", "Obstacle");
if (Physics.Raycast(transform.position, Vector3.down, 10f, mask))
{
    Debug.Log("Hit ground or obstacle");
}

Excluding a layer from a Culling Mask in code:

// Remove the "UI" layer from the main camera's culling mask
Camera.main.cullingMask &= ~(1 << LayerMask.NameToLayer("UI"));

TL;DR

  • Tags are text labels for identifying individual GameObjects at runtime.
  • Use CompareTag() instead of string equality for efficiency.
  • Layers (0-31) control physics collisions, camera culling, and raycast filtering.
  • LayerMask.GetMask() creates a bitmask from layer names for raycasts.