Menu
CoddyTech

Tags

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 57 of 85.

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

Light every street lamp when Space is pressed.

  1. Inside the Space if, get GameObject[] lamps = GameObject.FindGameObjectsWithTag("Lamp");.
  2. In foreach (GameObject lamp in lamps), set lamp.GetComponent<Renderer>().material.color = Color.yellow;.

Press Play and press Space: every lamp turns yellow, and the ball does not. Then Check.

Try it yourself

using UnityEngine;

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

All lessons in Unity Scripting Basics

Practice on your own: Unity playground