Tags and Layers
- Game Development course
- Beginner
- Lesson 23/83
- 4 min
Learn Tags and Layers and their role in collision filtering.
Tag concept
A Tag is a reference word used to identify and group GameObjects in the scene. For instance, the main character is tagged "Player", while enemies are tagged "Enemy".
// Safely checking an object's tag
if (collision.gameObject.CompareTag("Enemy")) {
Console.WriteLine("Enemy detected!");
}In code, the CompareTag method is much faster and more memory-friendly than direct string equality.
Layer concept
Layers are used to filter objects for physics collisions or camera rendering. For example, using the Layer Collision Matrix, you can prevent bullets from colliding with other bullets.
// Filtering specific layers using LayerMask
int uiLayer = LayerMask.NameToLayer("UI");In short: Tags identify objects logically, while Layers group objects for physics and camera operations.
Practice Print Tag and Layer information
Assign "Player" to tag and "Default" to layer. Print Tag: Player | Layer: Default to the console.
Starter code
using System;
class Program
{
static void Main()
{
// tag ve layer değerlerini tanımlayıp yazdır
}
}Sample solution
using System;
class Program
{
static void Main()
{
string tag = "Player";
string layer = "Default";
Console.WriteLine("Tag: " + tag + " | Layer: " + layer);
}
}Expected output
Tag: Player | Layer: Default
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the most performant and recommended way to check a GameObject's tag in code?
- Calling gameObject.CompareTag("Player") Correct answer
- Deleting and reloading all components
- Recreating all objects in the scene with a loop
- Searching the object with the mouse in Hierarchy
Explanation: CompareTag is the most efficient approach because it performs tag checks without internal string allocations.
2 Check object tag
if (target.____("Player"))
if (target.CompareTag("Player"))
Explanation: In Unity, the CompareTag function is used to verify an object's tag.
3 Tag and Layer differences
| Term | Meaning |
|---|---|
Tag |
Label for logically identifying objects |
Layer |
Layer for physics and camera filtering |
CompareTag |
Performant tag comparison function |
Collision Matrix |
Matrix defining which layers collide |