←All patterns
Game Programming

Component

Build entities by attaching small, single-purpose pieces of behaviour instead of growing a deep inheritance tree.

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.

Component Pattern
component scripts0subclasses needed0copied code0
tap a GameObject to select it
With inheritance1 classes
MonoBehaviour
└ Enemy
With components5 classes
HealthMoverFlyerShooterEnemyBrain
possible combinations: 31
Console
Press a button to see what happens…

Code

Assets / Scripts / Game Programming/ Component ›EnemyBrain.cs
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;
        }
    }
}
4 files · namespace Patterns.Game Programming.ComponentC# · UTF-8 · LF

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, Flyer and Gun are independent MonoBehaviours, and a flying shooter is simply a GameObject with all three.
  • Movement is behind the small IMover interface. Gun looks it up once with TryGetComponent, so the same Gun works 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.
Enemy.Before.cs → Enemy.After.cs+20/−19
11 using UnityEngine;
22
33 namespace Patterns.GameProgramming.Component
44 {
55 /// <summary>
6− /// Without components: every new kind of enemy is a new subclass, and
7− /// each one inherits everything above it, needed or not.
6+ /// With components: each ability is a small MonoBehaviour. A flying
7+ /// shooter is a GameObject with Health + Flyer + Gun, no subclass needed.
88 /// </summary>
9− public class Enemy : MonoBehaviour
9+ public class Health : MonoBehaviour
1010 {
11− [SerializeField] protected int maxHealth = 50;
12− [SerializeField] protected float speed = 3f;
11+ [SerializeField] private int maxHealth = 50;
1312
14− protected int health;
13+ private int health;
1514
16− protected virtual void Awake() => health = maxHealth;
15+ private void Awake() => health = maxHealth;
1716
1817 public void TakeDamage(int amount)
1918 {
2019 health -= amount;
2120 if (health <= 0) Destroy(gameObject);
2221 }
22+ }
2323
24− protected virtual void Move(Vector3 target)
25− {
26− Vector3 to = target - transform.position;
27− to.y = 0f;
28− transform.position += Vector3.ClampMagnitude(to, speed * Time.deltaTime);
29− }
24+ public interface IMover
25+ {
26+ void Move(Vector3 target);
3027 }
3128
32− public class FlyingEnemy : Enemy
29+ public class Flyer : MonoBehaviour, IMover
3330 {
34− [SerializeField] protected float altitude = 4f;
31+ [SerializeField] private float speed = 3f;
32+ [SerializeField] private float altitude = 4f;
3533
36− protected override void Move(Vector3 target)
34+ public void Move(Vector3 target)
3735 {
3836 target.y = altitude;
3937 transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
4038 }
4139 }
4240
43− public class ShootingFlyingEnemy : FlyingEnemy
41+ public class Gun : MonoBehaviour
4442 {
4543 [SerializeField] private Transform player;
4644 [SerializeField] private GameObject bulletPrefab;
4745 [SerializeField] private float cooldown = 1f;
4846
4947 private float nextShot;
48+ private IMover mover; // optional: a turret has none
5049
50+ private void Awake() => TryGetComponent(out mover);
51+
5152 private void Update()
5253 {
53− Move(player.position);
54+ mover?.Move(player.position);
5455
5556 if (Time.time >= nextShot)
5657 {
5758 Instantiate(bulletPrefab, transform.position, Quaternion.LookRotation(player.position - transform.position));
5859 nextShot = Time.time + cooldown;
5960 }
6061 }
6162 }
62− // Next sprint: ShootingWalkingEnemy, HealingFlyingEnemy, ShootingTurret (no Move)...
63+ // A Walker : MonoBehaviour, IMover is one more small file; every combination is free.
6364 }

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 Health bug is fixed once for players, enemies and crates alike.
  • Entities can gain or lose behaviour at runtime with AddComponent or 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 GetComponent calls every frame cost time, and missing components fail only at runtime.
  • Communication between components (who tells Health to play the hit animation?) needs a convention, such as events or interfaces, or it becomes ad-hoc coupling.

Tips

  1. 01Cache component lookups in Awake. Call GetComponent in Update only if the component can really change during play.
  2. 02Use [RequireComponent(typeof(Rigidbody))] for hard dependencies and TryGetComponent for optional ones, so a turret without a Mover still works.
  3. 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.
  4. 04Prefer events (Health.Died) for "something happened" and direct calls for "do this now"; it keeps components from reaching into each other’s internals.
  5. 05Keep shallow inheritance where it genuinely helps, such as an abstract Weapon with a few concrete weapons. Composition is about avoiding deep trees, not banning inheritance.