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, 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
MediumLight every street lamp when Space is pressed.
- Inside the Space
if, getGameObject[] lamps = GameObject.FindGameObjectsWithTag("Lamp");. - In
foreach (GameObject lamp in lamps), setlamp.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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground