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, ornull.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
MediumDusk 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.
}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon