# 5. Data-Driven Abilities with ScriptableObjects Part of [[Ability System]]. Previous: [[4. The Caster Validation Cast Times and Interrupts]]. Next: [[6. Ability Bar UI and Input]]. > [!warning] Code not compiled in Unity > Type-checked against 6000.5.8f1. No assets were created and nothing was run. ## 5.1 The assets ```csharp // Assets/Scripts/Abilities/AbilityAssets.cs using System.Collections.Generic; using UnityEngine; /// <summary>Designer-facing status effect. Converted once to an immutable StatusDef.</summary> [CreateAssetMenu(menuName = "Abilities/Status Effect", fileName = "Status_")] public sealed class StatusEffectDefinition : ScriptableObject { public string id = "burn"; [Min(0.05f)] public float duration = 4f; [Tooltip("0 = no periodic ticks.")] [Min(0f)] public float tickInterval = 1f; public StackPolicy stacking = StackPolicy.Refresh; [Min(1)] public int maxStacks = 1; public string[] tags = { "debuff" }; [Header("What it does")] [Tooltip("Damage per tick per stack. Negative heals.")] public float damagePerTick; [Tooltip("Multiplier on move speed while active (1 = none). Multiple slows multiply.")] [Range(0f, 2f)] public float moveSpeedMultiplier = 1f; public Color uiTint = Color.white; StatusDef _def; public StatusDef Def => _def ??= new StatusDef(id, duration, tickInterval, stacking, maxStacks, tags); void OnValidate() => _def = null; // edits in the Inspector rebuild the runtime def } /// <summary> /// One reusable thing an ability does. Abilities are lists of these, so a designer can build /// "fireball" = Damage + ApplyStatus(burn) without code. Effects are stateless assets. /// </summary> public abstract class AbilityEffect : ScriptableObject { public abstract void Apply(in AbilityContext context); } /// <summary>Everything an effect may need. Passed by readonly reference.</summary> public readonly struct AbilityContext { public AbilityContext(AbilityUser caster, GameObject target, Vector3 point, AbilityDefinition ability) { Caster = caster; Target = target; Point = point; Ability = ability; } public AbilityUser Caster { get; } public GameObject Target { get; } public Vector3 Point { get; } public AbilityDefinition Ability { get; } } /// <summary>Designer-facing ability: costs, cooldown, cast time, blocking tags, targeting, and effects.</summary> [CreateAssetMenu(menuName = "Abilities/Ability", fileName = "Ability_")] public sealed class AbilityDefinition : ScriptableObject { public enum Targeting { Self, AimedTarget, PointInFront } public string id = "fireball"; public string displayName = "Fireball"; public Sprite icon; [TextArea] public string description; [Header("Rules")] public string resourceId = "mana"; [Min(0f)] public float cost = 20f; [Min(0f)] public float cooldown = 5f; [Min(1)] public int charges = 1; [Min(0f)] public float castTime; public bool triggersGlobalCooldown = true; public bool interruptible = true; public string[] blockedByTags = { "stun", "silence" }; [Header("Targeting")] public Targeting targeting = Targeting.AimedTarget; [Min(0f)] public float range = 20f; public LayerMask targetMask = ~0; [Header("Effects (run in order)")] public List<AbilityEffect> effects = new List<AbilityEffect>(); public AbilitySpec ToSpec() => new AbilitySpec(id, resourceId, cost, cooldown, charges, castTime, triggersGlobalCooldown, interruptible, blockedByTags); } ``` - **`StatusEffectDefinition.Def`** builds the immutable `StatusDef` once and caches it. `OnValidate` clears the cache, so Inspector edits in Play Mode take effect on the next application. - **`AbilityDefinition.ToSpec()`** is the single place where designer data becomes engine rules. Talent modifiers (−20% cooldown, +10% cost) belong here: build a modified spec and `Grant` it again. - **`AbilityEffect`** is abstract and stateless. One `Effect_Damage25` asset can be shared by twenty abilities. Effects take an `in AbilityContext` (a readonly struct, passed by reference, so there's no copy and no garbage). ## 5.2 Effects ```csharp // Assets/Scripts/Abilities/AbilityEffects.cs using UnityEngine; /// <summary>Anything that can take damage or healing. SimpleHealth implements it; so can your existing health script.</summary> public interface IDamageable { void ApplyDamage(float amount, GameObject source); } [CreateAssetMenu(menuName = "Abilities/Effects/Damage", fileName = "Effect_Damage")] public sealed class DamageEffect : AbilityEffect { public float amount = 25f; public override void Apply(in AbilityContext context) { if (context.Target != null && context.Target.TryGetComponent<IDamageable>(out var d)) d.ApplyDamage(amount, context.Caster.gameObject); } } [CreateAssetMenu(menuName = "Abilities/Effects/Apply Status", fileName = "Effect_Status")] public sealed class ApplyStatusEffect : AbilityEffect { public StatusEffectDefinition status; public bool applyToSelf; public override void Apply(in AbilityContext context) { var who = applyToSelf ? context.Caster.gameObject : context.Target; if (status != null && who != null && who.TryGetComponent<AbilityUser>(out var user)) user.ApplyStatus(status, context.Caster); } } [CreateAssetMenu(menuName = "Abilities/Effects/Restore Resource", fileName = "Effect_Restore")] public sealed class RestoreResourceEffect : AbilityEffect { public string resourceId = "mana"; public float amount = 30f; public override void Apply(in AbilityContext context) => context.Caster.Caster.Resource(resourceId)?.Restore(amount); } [CreateAssetMenu(menuName = "Abilities/Effects/Dash", fileName = "Effect_Dash")] public sealed class DashEffect : AbilityEffect { public float distance = 6f; public override void Apply(in AbilityContext context) { var t = context.Caster.transform; var to = t.position + t.forward * distance; // Don't dash through walls: stop at the first hit. if (Physics.SphereCast(t.position + Vector3.up, 0.4f, t.forward, out var hit, distance, ~0, QueryTriggerInteraction.Ignore)) to = t.position + t.forward * Mathf.Max(0f, hit.distance - 0.1f); if (t.TryGetComponent<CharacterController>(out var cc)) cc.Move(to - t.position); else t.position = to; } } [CreateAssetMenu(menuName = "Abilities/Effects/Spawn VFX", fileName = "Effect_Vfx")] public sealed class SpawnVfxEffect : AbilityEffect { public GameObject prefab; public float lifetime = 2f; public bool atTarget = true; public override void Apply(in AbilityContext context) { if (prefab == null) return; var pos = atTarget && context.Target != null ? context.Target.transform.position : context.Point; var go = Object.Instantiate(prefab, pos, Quaternion.identity); Object.Destroy(go, lifetime); // swap for an ObjectPool in production } } /// <summary>Minimal health for testing. Replace with your own IDamageable.</summary> public sealed class SimpleHealth : MonoBehaviour, IDamageable { [SerializeField] float max = 100f; public float Current { get; private set; } public event System.Action<float, float> Changed; public event System.Action Died; void Awake() => Current = max; public void ApplyDamage(float amount, GameObject source) { if (Current <= 0f) return; Current = Mathf.Clamp(Current - amount, 0f, max); Changed?.Invoke(Current, max); if (Current <= 0f) Died?.Invoke(); } } ``` Adding a new kind of effect means adding one small class: `KnockbackEffect`, `SpawnProjectileEffect`, `PlaySoundEffect`, `AreaEffect` (an `OverlapSphereNonAlloc` that runs a nested effect list on each hit). Designers then mix them in the Inspector. That's *Command* from [[Game Programming Patterns (Review)]]: a request turned into an object you can store, reorder and reuse. `SpawnVfxEffect` uses `Instantiate` and `Destroy` to keep the sample short. Swap in a pool from [[3. Particle and VFX Pools]] before shipping. ## 5.3 AbilityUser ```csharp // Assets/Scripts/Abilities/AbilityUser.cs using System; using System.Collections.Generic; using UnityEngine; /// <summary> /// The Unity-side owner of an actor's abilities: resource pools, status container, caster rules, /// targeting, and running effect assets. Time comes from Time.timeAsDouble so pause (timeScale 0) /// freezes cooldowns and statuses alike. /// </summary> public sealed class AbilityUser : MonoBehaviour { [Serializable] public struct ResourceSetup { public string id; public float max; public float regenPerSecond; public float regenDelayAfterSpend; } [SerializeField] ResourceSetup[] resources = { new ResourceSetup { id = "mana", max = 100f, regenPerSecond = 5f, regenDelayAfterSpend = 1f } }; [SerializeField] AbilityDefinition[] startingAbilities; [SerializeField, Min(0f)] float globalCooldown = 1f; [SerializeField] Transform aimOrigin; readonly Dictionary<string, AbilityDefinition> _defs = new Dictionary<string, AbilityDefinition>(); readonly Dictionary<StatusDef, StatusEffectDefinition> _statusAssets = new Dictionary<StatusDef, StatusEffectDefinition>(); GameObject _pendingTarget; Vector3 _pendingPoint; public StatusContainer Statuses { get; private set; } public AbilityCaster Caster { get; private set; } public IReadOnlyDictionary<string, AbilityDefinition> Abilities => _defs; /// <summary>Raised with the result of every activation attempt, for UI and audio feedback.</summary> public event Action<AbilityDefinition, CastResult> ActivationAttempted; public event Action<AbilityDefinition> AbilityActivated; double Now => Time.timeAsDouble; void Awake() { Statuses = new StatusContainer(); Caster = new AbilityCaster(Statuses, globalCooldown); foreach (var r in resources) Caster.AddResource(new ResourcePool(r.id, r.max, r.regenPerSecond, r.regenDelayAfterSpend)); if (startingAbilities != null) { foreach (var a in startingAbilities) Grant(a); } Caster.Activated += OnActivated; Statuses.Ticked += OnStatusTicked; Statuses.Expired += s => { // Independent stacks share one def; forget the asset only when the last one is gone. if (Statuses.StacksOf(s.Def.Id) == 0) _statusAssets.Remove(s.Def); }; if (aimOrigin == null) aimOrigin = transform; } public void Grant(AbilityDefinition def) { if (def == null) return; _defs[def.id] = def; Caster.Grant(def.ToSpec()); } public CastResult TryActivate(string abilityId) { if (!_defs.TryGetValue(abilityId, out var def)) return CastResult.UnknownAbility; // Check the rules first, so a refused press never overwrites the target of a cast in progress. var check = Caster.Check(abilityId, Now); if (check != CastResult.Completed) { ActivationAttempted?.Invoke(def, check); return check; } // Targeting is resolved at press time; a cast-time ability lands on whatever was aimed at then. if (!ResolveTarget(def, out var target, out var point)) { ActivationAttempted?.Invoke(def, CastResult.Blocked); return CastResult.Blocked; } _pendingTarget = target; _pendingPoint = point; var result = Caster.TryActivate(abilityId, Now); ActivationAttempted?.Invoke(def, result); return result; } public void ApplyStatus(StatusEffectDefinition status, AbilityUser source) { var inst = Statuses.Apply(status.Def, source); if (inst != null) _statusAssets[status.Def] = status; } /// <summary>Product of every active status's move multiplier (stacks don't multiply again).</summary> public float MoveSpeedMultiplier() { var m = 1f; foreach (var s in Statuses.Active) { if (_statusAssets.TryGetValue(s.Def, out var asset)) m *= asset.moveSpeedMultiplier; } return m; } void Update() { var dt = Time.deltaTime; Statuses.Tick(dt); foreach (var r in resources) Caster.Resource(r.id)?.Tick(dt); Caster.Tick(Now); } bool ResolveTarget(AbilityDefinition def, out GameObject target, out Vector3 point) { target = null; point = transform.position; switch (def.targeting) { case AbilityDefinition.Targeting.Self: target = gameObject; return true; case AbilityDefinition.Targeting.PointInFront: point = transform.position + transform.forward * def.range; return true; default: var ray = new Ray(aimOrigin.position, aimOrigin.forward); if (Physics.Raycast(ray, out var hit, def.range, def.targetMask, QueryTriggerInteraction.Ignore)) { target = hit.collider.attachedRigidbody != null ? hit.collider.attachedRigidbody.gameObject : hit.collider.gameObject; point = hit.point; return true; } return false; // nothing aimed at: refuse before spending anything } } void OnActivated(AbilitySpec spec) { if (!_defs.TryGetValue(spec.Id, out var def)) return; var ctx = new AbilityContext(this, _pendingTarget, _pendingPoint, def); for (var i = 0; i < def.effects.Count; i++) { if (def.effects[i] != null) def.effects[i].Apply(ctx); } AbilityActivated?.Invoke(def); } void OnStatusTicked(StatusInstance s) { if (!_statusAssets.TryGetValue(s.Def, out var asset) || asset.damagePerTick == 0f) return; if (TryGetComponent<IDamageable>(out var d)) { var src = s.Source as AbilityUser; d.ApplyDamage(asset.damagePerTick * s.Stacks, src != null ? src.gameObject : null); } } } ``` ### Walkthrough - **One clock.** `Time.timeAsDouble` drives the caster and cooldowns, and `Time.deltaTime` drives statuses and regen. Both are *scaled* time, so pausing with `timeScale = 0` freezes everything consistently. (For a slow-motion ability that shouldn't slow the *player's* cooldowns, use unscaled time for the player's `AbilityUser`. That's a design call, so make it a field.) - **Check, then target, then activate.** `TryActivate` runs `Check` first, so a refused press can't overwrite the target of a cast that's in progress. Then it resolves targeting. An *aimed* ability with nothing under the crosshair is refused **before** any cost is paid. Then it calls the caster. - **Effects run on `Activated`**, which for cast-time abilities is when the cast completes. The target was captured at press time. If you want "lands on whatever you're aiming at when the cast ends", resolve the target again in `OnActivated`. - **Damage-over-time.** `OnStatusTicked` looks up the asset for that status and applies `damagePerTick × stacks` through `IDamageable`, credited to the source. - **`MoveSpeedMultiplier()`** multiplies the move multipliers of all active statuses, so two 0.7 slows give 0.49. If you want "strongest slow wins", take the minimum instead. Write that rule in your design doc. ## 5.4 Make the starter kit 1. **Create → Abilities → Status Effect**, three times: - `Status_Burning`: id `burning`, duration 4, tick 1, `StackAndRefresh`, max stacks 3, tags `debuff, burning`, damage per tick 5. - `Status_Slow`: id `slow`, duration 3, tick 0, `Independent`, max 2, tags `debuff, slow`, move multiplier 0.6. - `Status_Stun`: id `stun`, duration 1.5, `Refresh`, tags `debuff, stun`, move multiplier 0. 2. **Create → Abilities → Effects:** `Effect_Damage25` (amount 25), `Effect_ApplyBurning` (status = Burning), `Effect_ApplySlow`, `Effect_Dash6`, `Effect_RestoreMana50` (mana, 50). 3. **Create → Abilities → Ability:** - `Ability_Fireball`: cost 20, cooldown 5, cast 1.5, blocked by `stun, silence`, aimed, range 20. Effects: Damage25, ApplyBurning. - `Ability_Blink`: cost 10, cooldown 8, charges 2, cast 0, GCD off, interruptible off, blocked by `stun`, targeting Self. Effects: Dash6. - `Ability_Meditate`: cost 0, cooldown 30, cast 3, blocked by `stun, silence`, Self. Effects: RestoreMana50. 4. On the player: add **AbilityUser** (mana 100, regen 5/s, 1 s delay) and drag the three abilities into Starting Abilities. Set Aim Origin to the camera. 5. On a target dummy: add **SimpleHealth**, **AbilityUser** (so it can carry statuses) and a collider. ## 5.5 Wire statuses into movement ```csharp // Assets/Scripts/Abilities/StatusAwareMover.cs using UnityEngine; using UnityEngine.InputSystem; /// <summary>Example: a CharacterController mover that respects stun/root tags and slow multipliers.</summary> [RequireComponent(typeof(CharacterController), typeof(AbilityUser))] public sealed class StatusAwareMover : MonoBehaviour { [SerializeField] InputActionReference move; [SerializeField] float speed = 5f; CharacterController _cc; AbilityUser _abilities; void Awake() { _cc = GetComponent<CharacterController>(); _abilities = GetComponent<AbilityUser>(); } void OnEnable() => move.action.Enable(); void Update() { var input = move.action.ReadValue<Vector2>(); if (_abilities.Statuses.HasTag("stun") || _abilities.Statuses.HasTag("root")) input = Vector2.zero; if (input.sqrMagnitude > 0.01f && _abilities.Caster.IsCasting && _abilities.Caster.Casting.Interruptible) _abilities.Caster.Interrupt(); // stationary casts: moving cancels var dir = new Vector3(input.x, 0f, input.y); _cc.SimpleMove(dir * (speed * _abilities.MoveSpeedMultiplier())); } } ``` If you already have stats from [[Stat-Driven RPG Systems]], let a status *own* a stat modifier instead: add it on `Applied` and remove it on `Expired`. Then the slow shows up on the character sheet.