Menu
CoddyTech

Tags

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 43 of 67.

A tag is a label you give an object in the Inspector, picked from the list in the Tag Manager. Unity starts with a few (Player, MainCamera, Respawn, Finish and others) and you add your own. Many objects can share a tag, so tags group objects by role: every enemy, every coin, whatever each one is named. Three calls use them:

  • GameObject.FindWithTag("Player") returns one active object with the tag, or null.
  • GameObject.FindGameObjectsWithTag("Enemy") returns an array of every active object with the tag.
  • obj.CompareTag("Enemy") says whether one object has the tag.

This wave counter logs how many enemies the level starts with, however they are named:

void Start()
{
    GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
    Debug.Log("Enemies left: " + enemies.Length);
}

A tag must exist in the Tag Manager: FindGameObjectsWithTag("Enemey") throws UnityException: Tag: Enemey is not defined. To test one object, prefer CompareTag("Enemy") to tag == "Enemy": it is faster, and it reports a tag that does not exist instead of quietly answering false.

challenge icon

Challenge

Medium

Dusk falls on the street. When Space is pressed, every lamp lights up: set the color of every object tagged Lamp to Color.yellow. The lamps have different names, and the ball is not a lamp. Until Space is pressed, the lamps stay dark.

Press Play, click the game and press Space, then Check.

Try it yourself

using UnityEngine;

public class StreetLights : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            // Turn every object tagged Lamp yellow.
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics