What Is It?
The inheritance way to model enemies starts innocently: Enemy, then FlyingEnemy : Enemy, then ShootingFlyingEnemy : FlyingEnemy. Then design asks for a shooting walker, a healing flyer and a turret that shoots but never moves. Every new combination needs a new class, shared code gets pushed up into a bloated base class, and the tree grows combinatorially: five independent abilities can mix into 31 different kinds of entity.
The Component pattern flips this around. An entity is just a container, and each ability is a small object that does one thing: Health tracks hit points, Mover moves, Shooter fires, EnemyBrain decides. To get a flying shooter you attach a flying Mover and a Shooter; no new class is written. Five abilities means five components, whatever you combine them into.
Unity is this pattern. A GameObject is the container and every MonoBehaviour is a component. Components find each other with GetComponent/TryGetComponent, preferably through interfaces such as IDamageable, and [RequireComponent] declares hard dependencies so the editor adds them for you. Designers can then assemble new enemy types in a prefab without touching code.
When Is It Used?
Use it by default for anything that lives in a scene. Whenever you are about to write class X : SomethingEnemy just to add one ability, that ability probably wants to be its own component.
It is especially valuable when designers should build content: a library of Health, Mover, Shooter, Pickup, Interactable components plus prefab variants lets them invent new entities in the editor.
Do not split so far that a single concept is smeared across ten components that constantly query each other. If two pieces always appear together and share most of their state, one component is clearer than two.
Interactive Demo
Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.
Code
using UnityEngine;
namespace Patterns.GameProgramming.Component
{
/// <summary>
/// The AI component and entry point. It needs a Mover, uses a Shooter
/// only if one is attached, and reacts to Health if present. The same
/// brain drives a walker, a drone (Mover set to flying) or an unarmed scout.
/// </summary>
[RequireComponent(typeof(Mover))]
public class EnemyBrain : MonoBehaviour
{
[SerializeField] private Transform player;
[SerializeField] private float keepDistance = 6f;
private Mover mover;
private Shooter shooter; // optional
private Health health; // optional
private void Awake()
{
mover = GetComponent<Mover>();
TryGetComponent(out shooter);
TryGetComponent(out health);
}
private void OnEnable()
{
if (health != null) health.Died += OnDied;
}
private void OnDisable()
{
if (health != null) health.Died -= OnDied;
}
private void Update()
{
Vector3 away = (transform.position - player.position).normalized;
mover.Destination = player.position + away * keepDistance;
if (shooter != null)
shooter.TryShoot(player);
}
private void OnDied()
{
enabled = false;
mover.Destination = null;
}
}
}using System;
using UnityEngine;
namespace Patterns.GameProgramming.Component
{
/// <summary>Anything that can take a hit. Other components talk to it through this interface.</summary>
public interface IDamageable
{
void TakeDamage(int amount);
}
/// <summary>
/// One responsibility: hit points. It does not know whether its owner
/// walks, flies, shoots or is a crate.
/// </summary>
[DisallowMultipleComponent]
public class Health : MonoBehaviour, IDamageable
{
[SerializeField] private int maxHealth = 50;
public int Current { get; private set; }
public event Action Died;
private void Awake() => Current = maxHealth;
public void TakeDamage(int amount)
{
if (Current <= 0) return;
Current = Mathf.Max(0, Current - amount);
if (Current == 0)
Died?.Invoke();
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.Component
{
/// <summary>
/// One responsibility: moving toward a destination. Whoever decides where
/// to go (an AI, the player, a cutscene) just sets Destination.
/// </summary>
[RequireComponent(typeof(Rigidbody))]
public class Mover : MonoBehaviour
{
[SerializeField] private float speed = 4f;
[SerializeField] private bool flying;
private Rigidbody body;
public Vector3? Destination { get; set; }
private void Awake()
{
body = GetComponent<Rigidbody>();
body.useGravity = !flying;
}
private void FixedUpdate()
{
if (Destination is not Vector3 target) return;
Vector3 to = target - body.position;
if (!flying) to.y = 0f;
if (to.sqrMagnitude < 0.01f)
{
Destination = null;
return;
}
body.MovePosition(body.position + Vector3.ClampMagnitude(to, speed * Time.fixedDeltaTime));
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.Component
{
/// <summary>
/// One responsibility: firing at a target. It finds damageable things
/// through the IDamageable interface, never through a concrete class.
/// </summary>
public class Shooter : MonoBehaviour
{
[SerializeField] private int damage = 10;
[SerializeField] private float range = 12f;
[SerializeField] private float cooldown = 0.8f;
private float nextShotTime;
public bool TryShoot(Transform target)
{
if (Time.time < nextShotTime) return false;
Vector3 origin = transform.position;
Vector3 dir = target.position - origin;
if (!Physics.Raycast(origin, dir.normalized, out RaycastHit hit, range)) return false;
if (hit.collider.TryGetComponent(out IDamageable victim))
victim.TakeDamage(damage);
nextShotTime = Time.time + cooldown;
return true;
}
}
}Before & After
Real-world smell: an enemy hierarchy that needs a new subclass for every combination. Here is the code without the pattern, the refactored version, and the exact diff between them.
! What’s wrong with it?
ShootingFlyingEnemy inherits from FlyingEnemy, which inherits from Enemy. Health, movement and shooting are welded into one chain, and each level overrides Move or adds fields to its parent.
A shooting walker would need yet another subclass that copies the shooting code, and a turret that shoots but never moves cannot reuse ShootingFlyingEnemy without inheriting flight it does not want. Every new design request multiplies the classes, and a fix to shooting has to be repeated in each copy.
✓ What changed
- The chain is gone:
Health,FlyerandGunare independentMonoBehaviours, and a flying shooter is simply a GameObject with all three. - Movement is behind the small
IMoverinterface.Gunlooks it up once withTryGetComponent, so the sameGunworks on a flyer, a future walker, or a turret with no mover at all. - The shooting and health code is unchanged line for line; it just lives in its own class, so new enemy types are assembled in a prefab instead of written as subclasses.
using UnityEngine;
namespace Patterns.GameProgramming.Component
{
/// <summary>
/// Without components: every new kind of enemy is a new subclass, and
/// each one inherits everything above it, needed or not.
/// </summary>
public class Enemy : MonoBehaviour
{
[SerializeField] protected int maxHealth = 50;
[SerializeField] protected float speed = 3f;
protected int health;
protected virtual void Awake() => health = maxHealth;
public void TakeDamage(int amount)
{
health -= amount;
if (health <= 0) Destroy(gameObject);
}
protected virtual void Move(Vector3 target)
{
Vector3 to = target - transform.position;
to.y = 0f;
transform.position += Vector3.ClampMagnitude(to, speed * Time.deltaTime);
}
}
public class FlyingEnemy : Enemy
{
[SerializeField] protected float altitude = 4f;
protected override void Move(Vector3 target)
{
target.y = altitude;
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
}
public class ShootingFlyingEnemy : FlyingEnemy
{
[SerializeField] private Transform player;
[SerializeField] private GameObject bulletPrefab;
[SerializeField] private float cooldown = 1f;
private float nextShot;
private void Update()
{
Move(player.position);
if (Time.time >= nextShot)
{
Instantiate(bulletPrefab, transform.position, Quaternion.LookRotation(player.position - transform.position));
nextShot = Time.time + cooldown;
}
}
}
// Next sprint: ShootingWalkingEnemy, HealingFlyingEnemy, ShootingTurret (no Move)...
}using UnityEngine;
namespace Patterns.GameProgramming.Component
{
/// <summary>
/// With components: each ability is a small MonoBehaviour. A flying
/// shooter is a GameObject with Health + Flyer + Gun, no subclass needed.
/// </summary>
public class Health : MonoBehaviour
{
[SerializeField] private int maxHealth = 50;
private int health;
private void Awake() => health = maxHealth;
public void TakeDamage(int amount)
{
health -= amount;
if (health <= 0) Destroy(gameObject);
}
}
public interface IMover
{
void Move(Vector3 target);
}
public class Flyer : MonoBehaviour, IMover
{
[SerializeField] private float speed = 3f;
[SerializeField] private float altitude = 4f;
public void Move(Vector3 target)
{
target.y = altitude;
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
}
public class Gun : MonoBehaviour
{
[SerializeField] private Transform player;
[SerializeField] private GameObject bulletPrefab;
[SerializeField] private float cooldown = 1f;
private float nextShot;
private IMover mover; // optional: a turret has none
private void Awake() => TryGetComponent(out mover);
private void Update()
{
mover?.Move(player.position);
if (Time.time >= nextShot)
{
Instantiate(bulletPrefab, transform.position, Quaternion.LookRotation(player.position - transform.position));
nextShot = Time.time + cooldown;
}
}
}
// A Walker : MonoBehaviour, IMover is one more small file; every combination is free.
}Advantages & Disadvantages
+ Advantages
- Abilities combine freely, so the number of classes grows linearly with features instead of with every combination of them.
- Each component is small, focused and testable on its own; a
Healthbug is fixed once for players, enemies and crates alike. - Entities can gain or lose behaviour at runtime with
AddComponentor by enabling and disabling components, something an inheritance hierarchy cannot do.
− Disadvantages
- Behaviour is spread across several scripts, so understanding one entity means reading its whole component list instead of one class.
- Components that depend on each other need wiring; careless
GetComponentcalls every frame cost time, and missing components fail only at runtime. - Communication between components (who tells
Healthto play the hit animation?) needs a convention, such as events or interfaces, or it becomes ad-hoc coupling.
Tips
- 01Cache component lookups in
Awake. CallGetComponentinUpdateonly if the component can really change during play. - 02Use
[RequireComponent(typeof(Rigidbody))]for hard dependencies andTryGetComponentfor optional ones, so a turret without aMoverstill works. - 03Talk to other components through interfaces (
TryGetComponent(out IDamageable d)), so a crate, a player and a boss can all take damage without a shared base class. - 04Prefer events (
Health.Died) for "something happened" and direct calls for "do this now"; it keeps components from reaching into each other’s internals. - 05Keep shallow inheritance where it genuinely helps, such as an abstract
Weaponwith a few concrete weapons. Composition is about avoiding deep trees, not banning inheritance.