GameObjects, Components, Tags & Layers
Everything in a Unity scene is a GameObject: the player, a light, the camera, an invisible trigger, an empty folder object. A GameObject does almost nothing on its own. What it is comes from the components attached to it: a Transform (always present), a MeshRenderer to draw, a Rigidbody to fall, your own PlayerHealth script to take damage.
This is composition: instead of a class hierarchy like Enemy : Character : Actor, you build an enemy from parts. Swapping a part (a different movement component) changes behaviour without touching the others.
Components in code
using UnityEngine;
[RequireComponent(typeof(Rigidbody))] // Unity adds a Rigidbody if missing and won't let you remove it
public class Jumper : MonoBehaviour
{
[SerializeField] float jumpImpulse = 6f;
Rigidbody body;
void Awake()
{
body = GetComponent<Rigidbody>(); // look it up once and cache it
}
public void Jump()
{
body.AddForce(Vector3.up * jumpImpulse, ForceMode.Impulse);
}
void OnTriggerEnter(Collider other)
{
// TryGetComponent doesn't allocate when the component is missing (GetComponent can, in the editor).
if (other.TryGetComponent(out Coin coin))
coin.Collect();
}
}Other ways to find components:
| Call | Searches |
|---|---|
GetComponent<T>() / TryGetComponent(out T) |
this GameObject |
GetComponentInChildren<T>(), GetComponentInParent<T>() |
down or up the hierarchy (including itself) |
GetComponents<T>(list) |
every match, filling a list you reuse |
FindFirstObjectByType<T>(), FindAnyObjectByType<T>() |
the whole scene. Slow; use at startup only |
Migrating:
FindObjectOfType<T>()andFindObjectsOfType<T>()are obsolete in Unity 6. UseFindFirstObjectByType<T>()when you need a deterministic result,FindAnyObjectByType<T>()when any instance will do (faster), andFindObjectsByType<T>(FindObjectsSortMode.None)for all of them.
A model of GameObjects and components
using System;
using System.Collections.Generic;
var player = new GameObject("Player");
player.AddComponent<Health>().Max = 100;
player.AddComponent<Mover>();
Console.WriteLine(quot;components: {string.Join(", ", player.ComponentNames())}");
Console.WriteLine(quot;has Health? {player.TryGetComponent(out Health h)} (max {h?.Max})");
Console.WriteLine(quot;has Weapon? {player.TryGetComponent(out Weapon w)}");
// Composition: one more part gives the same object a new ability.
player.AddComponent<Weapon>().Damage = 12;
Console.WriteLine(quot;after AddComponent: {string.Join(", ", player.ComponentNames())}");
Console.WriteLine(quot;weapon owner: {player.GetComponent<Weapon>()!.GameObject.Name}");
class GameObject
{
public string Name;
readonly List<Component> components = new();
public GameObject(string name) { Name = name; AddComponent<Transform>(); } // every object has a Transform
public T AddComponent<T>() where T : Component, new()
{
var c = new T { GameObject = this };
components.Add(c);
return c;
}
public T? GetComponent<T>() where T : Component
{
foreach (var c in components) if (c is T t) return t;
return null;
}
public bool TryGetComponent<T>(out T? component) where T : Component
{
component = GetComponent<T>();
return component != null;
}
public IEnumerable<string> ComponentNames() { foreach (var c in components) yield return c.GetType().Name; }
}
abstract class Component { public GameObject GameObject = null!; }
class Transform : Component { }
class Health : Component { public int Max; }
class Mover : Component { }
class Weapon : Component { public int Damage; }components: Transform, Health, Mover
has Health? True (max 100)
has Weapon? False
after AddComponent: Transform, Health, Mover, Weapon
weapon owner: Player
Tags
A tag is one string label per GameObject (Player, Respawn, Finish, plus your own, added under Project Settings > Tags and Layers). Compare tags with CompareTag, which doesn't allocate a string:
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player")) OpenDoor(); // not: other.tag == "Player"
}Tags are fine for "is this the player?". For anything richer, check for a component instead (TryGetComponent(out IDamageable target)): it carries data and can't be misspelled.
Layers and layer masks
A GameObject also has one layer (32 slots, a few built in, the rest yours). Layers drive three systems: which cameras render the object (culling mask), which objects collide (the collision matrix) and which objects a raycast can hit. A layer mask is a 32-bit integer with one bit per layer:
using System;
string[] layers = new string[32];
layers[0] = "Default"; layers[2] = "Ignore Raycast"; layers[5] = "UI";
layers[6] = "Ground"; layers[7] = "Enemy"; layers[8] = "Pickup";
int GetMask(params string[] names) // like LayerMask.GetMask
{
int mask = 0;
foreach (var n in names) mask |= 1 << Array.IndexOf(layers, n);
return mask;
}
int groundAndEnemies = GetMask("Ground", "Enemy");
Console.WriteLine(quot;mask = {groundAndEnemies} = {Convert.ToString(groundAndEnemies, 2).PadLeft(10, '0')}");
foreach (int layer in new[] { 0, 6, 7, 8 })
{
bool hit = (groundAndEnemies & (1 << layer)) != 0;
Console.WriteLine(quot;{layers[layer],-8} (layer {layer}) included: {hit}");
}
int everythingButPickups = ~GetMask("Pickup");
Console.WriteLine(quot;includes Pickup after ~: {(everythingButPickups & (1 << 8)) != 0}");mask = 192 = 0011000000
Default (layer 0) included: False
Ground (layer 6) included: True
Enemy (layer 7) included: True
Pickup (layer 8) included: False
includes Pickup after ~: False
In Unity, expose a [SerializeField] LayerMask groundMask; field and tick layers in the Inspector, or build one with LayerMask.GetMask("Ground", "Enemy"). Don't confuse the two: gameObject.layer is a layer index (6), while a mask is bits (1 << 6).
Test yourself
Which is the Unity 6 replacement for the obsolete FindObjectOfType<T>() when any instance will do?
FindAnyObjectByType<T>()GameObject.Find<T>()GetComponentInScene<T>()FindObjectOfTypeFast<T>()
A layer mask includes layers 6 and 7. What is its integer value?
- 13
- 67
- 192
- 42
Why prefer other.CompareTag("Player") to other.tag == "Player"?
- It is case-insensitive
- It avoids allocating a new string each call
- It also checks the layer
tagis obsolete