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.
Code
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();
}
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.SubclassSandbox
{
/// <summary>
/// The sandbox base class. It owns every engine dependency and exposes a
/// small protected toolbox. Subclasses only implement Activate().
/// </summary>
[RequireComponent(typeof(Rigidbody))]
public abstract class Superpower : MonoBehaviour
{
[SerializeField] private AudioSource audioSource;
[SerializeField] private ParticleSystem particles;
[SerializeField] private LayerMask targetMask = ~0;
[SerializeField] private float cooldown = 1f;
private Rigidbody body;
private float readyAt;
private static readonly Collider[] Hits = new Collider[16];
protected virtual void Awake() => body = GetComponent<Rigidbody>();
/// <summary>Called by input code. Handles cooldown, then runs the subclass.</summary>
public void TryActivate()
{
if (Time.time < readyAt) return;
readyAt = Time.time + cooldown;
Activate();
}
/// <summary>The sandbox method: the only thing a subclass must write.</summary>
protected abstract void Activate();
// ---------- the toolbox ----------
protected void PlaySound(AudioClip clip, float volume = 1f) =>
audioSource.PlayOneShot(clip, volume);
protected void SpawnParticles(int count) => particles.Emit(count);
protected void MoveBy(Vector3 velocityChange) =>
body.AddForce(velocityChange, ForceMode.VelocityChange);
protected Vector3 Forward => transform.forward;
/// <summary>Damages every Health in range; returns how many were hit.</summary>
protected int DealDamage(float radius, int amount)
{
int count = Physics.OverlapSphereNonAlloc(transform.position, radius, Hits, targetMask);
int hit = 0;
for (int i = 0; i < count; i++)
{
if (Hits[i].TryGetComponent(out Health health) && health.gameObject != gameObject)
{
health.Change(-amount);
hit++;
}
}
return hit;
}
protected void HealSelf(int amount)
{
if (TryGetComponent(out Health health)) health.Change(amount);
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.SubclassSandbox
{
/// <summary>A quick forward burst. Written only with toolbox calls.</summary>
public class Dash : Superpower
{
[SerializeField] private AudioClip whoosh;
[SerializeField] private float strength = 12f;
protected override void Activate()
{
PlaySound(whoosh);
SpawnParticles(10);
MoveBy(Forward * strength);
}
}
/// <summary>Hops up, then damages everything around the landing spot.</summary>
public class GroundSlam : Superpower
{
[SerializeField] private AudioClip boom;
[SerializeField] private float radius = 4f;
[SerializeField] private int damage = 25;
protected override void Activate()
{
MoveBy(Vector3.up * 6f);
PlaySound(boom);
SpawnParticles(40);
DealDamage(radius, damage);
}
}
/// <summary>Restores health. Note: no reference to Health, AudioSource or particles.</summary>
public class Heal : Superpower
{
[SerializeField] private AudioClip chime;
[SerializeField] private int amount = 30;
protected override void Activate()
{
PlaySound(chime, 0.6f);
SpawnParticles(15);
HealSelf(amount);
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.SubclassSandbox
{
/// <summary>
/// A plain engine-side system. Only the Superpower base class talks to it,
/// so abilities never depend on it directly.
/// </summary>
public class Health : MonoBehaviour
{
[SerializeField] private int max = 100;
public int Current { get; private set; }
private void Awake() => Current = max;
public void Change(int delta)
{
Current = Mathf.Clamp(Current + delta, 0, max);
if (Current == 0) Debug.Log($"{name} was defeated");
}
}
}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
GroundSlamnow derives fromSuperpowerinstead ofMonoBehaviour.- The cached
audioSource,particlesandbodyfields and theAwakelookups are gone; the base class owns them. TryActivateand the cooldown move to the base class, and the ability only overridesActivate().- The body is four toolbox calls:
MoveBy,PlaySound,SpawnParticlesandDealDamage, which hides the allocation-freeOverlapSphereNonAllocquery behind one helper.
using UnityEngine;
namespace Patterns.GameProgramming.SubclassSandbox
{
/// <summary>
/// Without Subclass Sandbox: the ability grabs every engine system it
/// needs and drives them directly. Dash, Heal and friends do the same.
/// </summary>
public class GroundSlam : MonoBehaviour
{
[SerializeField] private AudioClip boom;
[SerializeField] private float radius = 4f;
[SerializeField] private int damage = 25;
[SerializeField] private float cooldown = 1f;
private AudioSource audioSource;
private ParticleSystem particles;
private Rigidbody body;
private float readyAt;
private void Awake()
{
audioSource = GetComponent<AudioSource>();
particles = GetComponentInChildren<ParticleSystem>();
body = GetComponent<Rigidbody>();
}
public void TryActivate()
{
if (Time.time < readyAt) return;
readyAt = Time.time + cooldown;
body.AddForce(Vector3.up * 6f, ForceMode.VelocityChange);
audioSource.PlayOneShot(boom);
particles.Emit(40);
foreach (Collider hit in Physics.OverlapSphere(transform.position, radius))
{
if (hit.TryGetComponent(out Health health) && health.gameObject != gameObject)
health.Change(-damage);
}
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.SubclassSandbox
{
/// <summary>
/// With Subclass Sandbox: the ability is written only in terms of the
/// protected toolbox that Superpower provides.
/// </summary>
public class GroundSlam : Superpower
{
[SerializeField] private AudioClip boom;
[SerializeField] private float radius = 4f;
[SerializeField] private int damage = 25;
protected override void Activate()
{
MoveBy(Vector3.up * 6f);
PlaySound(boom);
SpawnParticles(40);
DealDamage(radius, damage);
}
}
}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 : Superpowerget messy.
Tips
- 01Make the toolbox
protectedand non-virtual so subclasses can call it but not reshape it, and make the public entry point (TryActivate) non-virtual too. - 02Keep helpers thin: forward to existing systems instead of reimplementing them in the base class.
- 03If the toolbox gets big, split it into small helper objects the base class exposes (
Audio.Play,Fx.Emit) rather than one huge class. - 04Prefer
[RequireComponent]on the base class so every subclass inherits its component requirements automatically. - 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.