←All patterns
Game Programming

Subclass Sandbox

Give a base class a small toolbox of protected operations and write every subclass only in terms of that toolbox.

What Is It?

Subclass Sandbox puts one base class between your many small behaviours and the rest of the engine. The base class owns the dependencies (audio, particles, physics, health) and offers them as protected helper methods: PlaySound, SpawnParticles, MoveBy, DealDamage. It also declares one abstract sandbox method, here Activate().

Each subclass, such as Dash, GroundSlam or Heal, overrides Activate() and builds its effect purely from those helpers. It never calls GetComponent<AudioSource>() or touches a Rigidbody. The base class is the only place that knows how a sound is actually played.

The result is a fan of dozens of tiny classes that are coupled to one thing, the base class, instead of to five engine systems each. When the audio system changes, you fix PlaySound once, not forty abilities.

When Is It Used?

Use it when you have many sibling behaviours of the same shape: superpowers, spells, weapon abilities, card effects, AI actions, tutorial steps.

It fits well when a lot of people (or modders) write those behaviours and you want them to stay inside a safe, documented set of operations. The toolbox doubles as the API reference.

Avoid it when the subclasses have little in common, or when you would rather compose behaviour from data. If the toolbox keeps growing because every new ability needs one more special helper, the base class is turning into a god object.

Interactive Demo

Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.

Subclass Sandbox Pattern
toolbox calls0engine deps in subclass0
Superpower
abstract base · toolbox
#PlaySound()
#SpawnParticles()
#MoveBy()
#DealDamage()
#HealSelf()
💥 GroundSlam
: Superpower
Activate() {
MoveBy
PlaySound
SpawnParticles
DealDamage
}
AudioSource
ParticleSystem
Rigidbody
Health
self
enemy
Console
Press a button to see what happens…

Code

Assets / Scripts / Game Programming/ SubclassSandbox ›PowerInput.cs
using UnityEngine;

namespace Patterns.GameProgramming.SubclassSandbox
{
    /// <summary>
    /// Client: binds keys to whatever superpowers are on this GameObject.
    /// It only knows the public TryActivate() of the base class.
    /// </summary>
    public class PowerInput : MonoBehaviour
    {
        [SerializeField] private Superpower[] powers;

        private void Reset() => powers = GetComponents<Superpower>();

        private void Update()
        {
            for (int i = 0; i < powers.Length && i < 9; i++)
            {
                if (Input.GetKeyDown(KeyCode.Alpha1 + i))
                    powers[i].TryActivate();
            }
        }
    }
}
4 files · namespace Patterns.Game Programming.SubclassSandboxC# · UTF-8 · LF

Before & After

Real-world smell: abilities that each reach into every engine system. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

GroundSlam fetches an AudioSource, a ParticleSystem and a Rigidbody in Awake, handles its own cooldown, and runs Physics.OverlapSphere and Health.Change inline. Dash and Heal repeat most of the same lookups.

Every ability is coupled to four engine systems, so moving to pooled audio or a new damage pipeline means editing every ability file. Small rules such as the cooldown drift apart between copies, and a missing component only shows up as a NullReferenceException in play.

✓ What changed

  • GroundSlam now derives from Superpower instead of MonoBehaviour.
  • The cached audioSource, particles and body fields and the Awake lookups are gone; the base class owns them.
  • TryActivate and the cooldown move to the base class, and the ability only overrides Activate().
  • The body is four toolbox calls: MoveBy, PlaySound, SpawnParticles and DealDamage, which hides the allocation-free OverlapSphereNonAlloc query behind one helper.
GroundSlam.Before.cs → GroundSlam.After.cs+8/−29
11 using UnityEngine;
22
33 namespace Patterns.GameProgramming.SubclassSandbox
44 {
55 /// <summary>
6− /// Without Subclass Sandbox: the ability grabs every engine system it
7− /// needs and drives them directly. Dash, Heal and friends do the same.
6+ /// With Subclass Sandbox: the ability is written only in terms of the
7+ /// protected toolbox that Superpower provides.
88 /// </summary>
9− public class GroundSlam : MonoBehaviour
9+ public class GroundSlam : Superpower
1010 {
1111 [SerializeField] private AudioClip boom;
1212 [SerializeField] private float radius = 4f;
1313 [SerializeField] private int damage = 25;
14− [SerializeField] private float cooldown = 1f;
1514
16− private AudioSource audioSource;
17− private ParticleSystem particles;
18− private Rigidbody body;
19− private float readyAt;
20−
21− private void Awake()
15+ protected override void Activate()
2216 {
23− audioSource = GetComponent<AudioSource>();
24− particles = GetComponentInChildren<ParticleSystem>();
25− body = GetComponent<Rigidbody>();
17+ MoveBy(Vector3.up * 6f);
18+ PlaySound(boom);
19+ SpawnParticles(40);
20+ DealDamage(radius, damage);
2621 }
27−
28− public void TryActivate()
29− {
30− if (Time.time < readyAt) return;
31− readyAt = Time.time + cooldown;
32−
33− body.AddForce(Vector3.up * 6f, ForceMode.VelocityChange);
34− audioSource.PlayOneShot(boom);
35− particles.Emit(40);
36−
37− foreach (Collider hit in Physics.OverlapSphere(transform.position, radius))
38− {
39− if (hit.TryGetComponent(out Health health) && health.gameObject != gameObject)
40− health.Change(-damage);
41− }
42− }
4322 }
4423 }

Advantages & Disadvantages

+ Advantages

  • Subclasses depend only on the base class, so engine changes are made in one place.
  • Writing a new ability is short and safe: override one method, call a few helpers.
  • Common rules (cooldowns, logging, networking checks) live in the base class and apply to every ability automatically.

− Disadvantages

  • The base class tends to grow into a large class that knows about every system in the game.
  • Every subclass is coupled to the base class; changing a helper signature touches all of them (the fragile base class problem).
  • Deep inheritance in Unity fights the component model; one ability per component is fine, but chains like FireDash : Dash : Superpower get messy.

Tips

  1. 01Make the toolbox protected and non-virtual so subclasses can call it but not reshape it, and make the public entry point (TryActivate) non-virtual too.
  2. 02Keep helpers thin: forward to existing systems instead of reimplementing them in the base class.
  3. 03If the toolbox gets big, split it into small helper objects the base class exposes (Audio.Play, Fx.Emit) rather than one huge class.
  4. 04Prefer [RequireComponent] on the base class so every subclass inherits its component requirements automatically.
  5. 05Template Method is a close cousin: there the base class fixes the order of steps; in Subclass Sandbox the subclass decides the order and the base provides the tools.