Below is one way to structure a highly-modular, animation-tight 2D combat platformer in Unity.
I’m keeping it “engineer-friendly” but still approachable—no over-engineered generic voodoo, yet enough typing safety that you don’t lose your mind when the project scales.
1. Core Mental Model
Actor (player, enemy, boss)
└── State‐Machine (Ground, Air, Wall, Climb, Hurt, …)
└── Input → Ability Map ( per state )
└── Ability Asset
• Animation Timeline (clip + per-frame data)
• Hit/Hurt boxes per frame
• Movement curves / forces
• Extra custom logic (events)
Everything that is “designer-tweakable” lives in a ScriptableObject.
Everything that is “runtime” lives on the Actor or on lightweight runner components that read those SOs.
2. Top-Level Classes / Interfaces (C# pseudo-code)
public interface IActorContext
{
Rigidbody2D Body { get; }
Animator Animator { get; }
Transform Transform { get; }
// … any shared stuff: health, stamina, etc.
}
public abstract class Ability : ScriptableObject
{
public AnimationClip clip;
public FrameTable frameTable; // hit/hurt boxes + events
public Curve movementCurve;
// Descriptive meta -> which inputs trigger it, cost, cooldown…
public virtual bool CanStart(IActorContext ctx) => true;
public abstract void StartAbility(IActorContext ctx);
public abstract void UpdateAbility(IActorContext ctx, float timeInState);
public abstract void EndAbility(IActorContext ctx);
}
public abstract class ActorState
{
protected IActorContext ctx;
protected Dictionary<InputId, Ability> abilityMap;
public ActorState(IActorContext ctx, Dictionary<InputId, Ability> map)
{ this.ctx = ctx; abilityMap = map; }
public virtual void Enter() {}
public virtual void Exit() {}
public virtual void Tick() {}
public virtual ActorState EvaluateTransition() => null; // return new state or null
}
• Ability is purely data + a little logic.
• ActorState owns the per-state input→ability map.
• ActorStateMachine component just swaps states, feeds Tick() in FixedUpdate, and passes InputBuffer.
No character-specific subclasses are needed unless you actually need new data.
If “Slug” wants its own slimy dash ability, make a SlugDashAbility ScriptableObject and assign it; the framework stays the same.
3. Input → Ability Binding (state-local)
enum InputId { TiltLR, TiltUp, Dash, Attack, Special, JumpHoldDown }
[CreateAssetMenu]
public class StateActionMap : ScriptableObject
{
public ActorStateId state; // e.g. Ground, Air …
public List<Binding> bindings;
[Serializable] public struct Binding
{
public InputId input;
public Ability ability;
}
}
Each StateActionMap asset lives on the actor prefab, so a Player, Slug, or Boss can swap out whatever ability asset for a given input without touching code.
4. Animation-Tight Hit/Hurt Boxes (no slow animation events)
Problem: AnimationEvent fires after the animation system; physics has already stepped.
Solution: you drive the timeline yourself and create/destroy hitboxes on deterministic frame counts inside FixedUpdate.
[Serializable]
public struct FrameTableRow
{
public int frame; // keyframe index or time * fps
public HitboxPreset hitbox; // ScriptableObject or prefab
public HurtboxPreset hurtbox; // optional
public bool spawn; // true = spawn, false = despawn
}
[CreateAssetMenu]
public class FrameTable : ScriptableObject
{
public int fps = 60; // sampling rate
public List<FrameTableRow> rows;
}
AbilityRunner (runtime helper attached on the actor):
void FixedUpdate()
{
if (!currentAbility) return;
timeInAbility += Time.fixedDeltaTime;
int logicalFrame = Mathf.FloorToInt(timeInAbility * frameTable.fps);
// process any frame events scheduled at this frame
foreach(var row in frameTable.rows)
{
if(row.frame == logicalFrame)
{
if(row.spawn) SpawnBox(row);
else DespawnBox(row);
}
}
}
Because you operate in FixedUpdate, you’re synced with physics 100 %.
Designer sets exact frames in the FrameTable asset, no animator “events” needed.
5. Moving the Character While the Ability Plays
Use a movementCurve (time 0→1 vs velocity) inside the Ability asset:
public override void UpdateAbility(IActorContext ctx, float t)
{
float vx = movementCurve.Evaluate(t); // e.g. dash forward curve
ctx.Body.velocity = new Vector2(vx * ctx.Transform.localScale.x, ctx.Body.velocity.y);
}
If you need fancier (e.g. root-motion platformer), cache the original position and lerp; same idea, but you’re in full control.
6. Strong Typing Without Generic Hell
- Common Interface: Anything needing the context just receives
IActorContext ctx.
- Custom Extension: If Slug needs extra goo, create
ISlugContext : IActorContext with slug-only fields; Slug-specific abilities SlugDash can safely ctx as ISlugContext.
- Minimal Generics: Optional –
ActorState<TCtx> where TCtx : IActorContext. But usually a single interface + safe casts is enough, and you avoid template noise in the editor.
7. Putting It All Together (Flow)
- Input System callback sticks raw input into
InputBuffer (timestamped).
- StateMachine.Tick() (FixedUpdate)
a. CurrentState.Tick()
b. Inside Tick(), query InputBuffer → look for mapped ability in abilityMap.
c. If ability.CanStart(ctx) and not already playing one → call AbilityRunner.Start(ability).
d. AbilityRunner handles animation (Animator.Play), frame timeline, forces, SFX, etc.
e. State.EvaluateTransition() decides when to switch to a different movement state (ground→air if !isGrounded, etc.).
8. Example: Ground Dash vs Air Dash
Player prefab
• Animator
• ActorStateMachine (references GroundStateSO, AirStateSO)
• StateActionMaps
– Ground map: Dash → GroundDashAbility
– Air map: Dash → AirDashAbility
Designer tweaks each ability’s data independently (speed, animation, hitboxes).
Same button, different result, zero extra code.
9. Custom Editor Helpers (huge QoL)
- FrameTable editor window: scrub through the animation clip, click to add hitbox/hurtbox rows, save directly to the asset.
- Ability preview window: play the ability timeline in edit mode, visually see hitboxes appear.
- StateActionMap inspector: drag InputId enum + Ability asset.
These are not required on day one, but once you’ve proven the runtime path, build tools early—they pay back fast.
10. Checklist
✅ All gameplay-critical timing lives in FixedUpdate, not animation events.
✅ Abilities are pure data; can be shared/re-used.
✅ States own the “which ability for which input” mapping.
✅ You can extend context per actor without duplicating the framework.
✅ Designers/artists never touch code; they assemble ScriptableObjects.
TL;DR
- Build a small but solid state machine + ability system driven by ScriptableObjects.
- Let each state map inputs → ability assets, so Ground/Air/Wall can all reuse the same buttons differently.
- Drive hit/hurt boxes off a FrameTable in FixedUpdate—not AnimationEvents—for deterministic combat.
- Use a thin
IActorContext interface to access common components; cast to extended interfaces only when needed—no crazy generics.
- Add editor tooling once the pipeline works.
That architecture scales from a player prototype all the way to a 20-enemy roster without forcing you to rewrite or duplicate anything. Happy hacking, and may your hitboxes always land! 🎮⚔️