JSON INTEGRATION

Unity & Godot step-by-step

On this page▾
Engine-agnostic data

Use StatsForge JSON in your game

StatsForge exports a portable JSON document that any engine can consume. Each entity (character, weapon, enemy, item) is a single file containing an id, a human name, an ordered list of stats, and a list of modifiers. This guide walks you through using that file in Unity and Godot.

File:stats_forge/data/knight.json
JSON
{
  "entity": {
    "id": "knight",
    "name": "Knight",
    "stats": [
      { "id": "health",  "baseValue": 120, "min": 0, "max": 999, "growth": 12,
        "regen": { "type": "flat", "value": 2.5 } },
      { "id": "damage",  "baseValue": 18,  "min": 0, "max": 400, "growth": 2  },
      { "id": "defense", "baseValue": 10,  "min": 0, "max": 200, "growth": 1  }
    ],
    "modifiers": [
      { "id": "knight_iron_will", "name": "Iron Will", "target": "health",
        "operation": "percent", "value": 10, "active": true }
    ],
    "items": [],
    "skills": []
  }
}

Export envelope

Every export is a single file with one entity plus the definitions it references. entity.items[] and entity.skills[] are references only — the real data lives in itemDefinitions, effectDefinitions and skillDefinitions.

Complexity profiles & runtime requirements

Complexity profiles & runtime requirements

The calculation pipeline is identical across profiles — higher profiles only add more stats and more modifier kinds. Implement Advanced once and downscale by not registering unused stats.

ProfileStats shippedRuntime requirements
Simplehealth, staminabase + clamp(min, max)
Intermediate+ damage, defense+ add / percent modifiers, basic combat formula
Advanced+ mana, crit, attack speed, movement speed+ multiply modifiers, conditions, item linking
Customdesigner-defined (any combination)superset of Advanced
Engine
Classes only — step by step

Classes only — step by step

Start here when your game has character classes, enemies or bosses but no equipment. Follow the four steps in order; each one builds on the previous file.

Final project structure

Drop your StatsForge .json exports inside Assets/Resources/Entities/ so Unity can stream them as TextAsset.

Tree
Assets
└── Resources
    └── StatsForge
        ├── Data                 (.json exports)
        │   ├── knight.json
        │   └── ancient_dragon.json
        └── Scripts
            ├── Data             (POCOs deserialized from JSON)
            │   ├── StatData.cs
            │   ├── Modifier.cs
            │   ├── ModifierCondition.cs
            │   ├── DefModifier.cs
            │   ├── ItemDefinition.cs
            │   ├── EffectDefinition.cs
            │   ├── SkillDefinition.cs
            │   ├── EntityData.cs
            │   └── EntityBundle.cs
            ├── Loading
            │   └── EntityLoader.cs
            └── Gameplay
                ├── CharacterClass.cs
                ├── EffectRunner.cs
                └── SkillCaster.cs

1 · Data models

Create these four C# classes. Field names match the JSON keys exactly so JsonUtility can deserialize them.

File:Assets/StatsForge/Scripts/Data/EntityData.cs
C#
using System.Collections.Generic;
using Newtonsoft.Json;

namespace StatsForge.Data
{
    public sealed class RegenData
    {
        [JsonProperty("type")]  public string Type  { get; set; } // flat | percent
        [JsonProperty("value")] public float  Value { get; set; }
    }

    public sealed class StatData
    {
        [JsonProperty("id")]        public string Id        { get; set; }
        [JsonProperty("baseValue")] public float  BaseValue { get; set; }
        [JsonProperty("min")]       public float  Min       { get; set; }
        [JsonProperty("max")]       public float  Max       { get; set; }
        [JsonProperty("growth")]    public float  Growth    { get; set; }
        [JsonProperty("regen")]     public RegenData Regen   { get; set; } // null = no regeneration
    }

    public sealed class ModifierCondition
    {
        [JsonProperty("type")]      public string Type      { get; set; }
        [JsonProperty("threshold")] public float  Threshold { get; set; }
    }

    public sealed class Modifier
    {
        [JsonProperty("id")]        public string Id        { get; set; }
        [JsonProperty("name")]      public string Name      { get; set; }
        [JsonProperty("target")]    public string Target    { get; set; }
        [JsonProperty("operation")] public string Operation { get; set; } // add | subtract | percent | multiply
        [JsonProperty("value")]     public float  Value     { get; set; }
        [JsonProperty("active")]    public bool   Active    { get; set; } = true;
        [JsonProperty("condition")] public ModifierCondition Condition { get; set; }
    }

    public sealed class ItemRef
    {
        [JsonProperty("itemId")]   public string Id       { get; set; }
        [JsonProperty("equipped")] public bool   Equipped { get; set; } = true;
    }

    public sealed class SkillRef
    {
        [JsonProperty("skillId")] public string Id { get; set; }
    }

    public sealed class EntityData
    {
        [JsonProperty("id")]        public string         Id        { get; set; }
        [JsonProperty("name")]      public string         Name      { get; set; }
        [JsonProperty("stats")]     public List<StatData> Stats     { get; set; } = new();
        [JsonProperty("modifiers")] public List<Modifier> Modifiers { get; set; } = new();
        [JsonProperty("items")]     public List<ItemRef>  Items     { get; set; } = new();
        [JsonProperty("skills")]    public List<SkillRef> Skills    { get; set; } = new();
    }
}

2 · Entity loader

Add a loader to read entities from Resources/Entities/ by id.

File:Assets/StatsForge/Scripts/Loading/EntityLoader.cs
C#
using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;

namespace StatsForge.Data
{
    /// Loaded bundle with every definition indexed by id.
    public sealed class LoadedBundle
    {
        public EntityData Entity;
        public Dictionary<string, ItemDefinition>   Items   = new();
        public Dictionary<string, EffectDefinition> Effects = new();
        public Dictionary<string, SkillDefinition>  Skills  = new();
    }

    public static class EntityLoader
    {
        // Loads Assets/Resources/StatsForge/Data/<id>.json
        public static LoadedBundle Load(string id)
        {
            var asset = Resources.Load<TextAsset>($"StatsForge/Data/{id}");
            if (asset == null)
            {
                Debug.LogError($"[StatsForge] export not found: {id}");
                return null;
            }

            var raw = JsonConvert.DeserializeObject<EntityBundle>(asset.text);
            if (raw?.Entity == null)
            {
                Debug.LogError($"[StatsForge] missing \"entity\" in {id}.json");
                return null;
            }

            var bundle = new LoadedBundle { Entity = raw.Entity };
            foreach (var i in raw.ItemDefinitions)   bundle.Items[i.Id]   = i;
            foreach (var e in raw.EffectDefinitions) bundle.Effects[e.Id] = e;
            foreach (var s in raw.SkillDefinitions)  bundle.Skills[s.Id]  = s;
            return bundle;
        }
    }
}

3 · Use it in gameplay

Lookup stats by id, read baseValue, then apply each active modifier.

File:Assets/StatsForge/Scripts/Gameplay/CharacterClass.cs
C#
using System.Collections.Generic;
using UnityEngine;
using StatsForge.Gameplay;

namespace StatsForge.Data
{
    /// A runtime character. Stats are cached on Awake and recomputed on demand.
    public sealed class CharacterClass : MonoBehaviour
    {
        public EntityData Data;
        public int Level = 1;
        public EffectRunner Effects;   // optional: active modifier effects

        readonly Dictionary<string, StatData> _stats = new();
        readonly List<ItemDefinition> _items = new();

        public IReadOnlyList<ItemDefinition> LinkedItems => _items;

        void Awake()
        {
            if (Data == null) return;
            foreach (var s in Data.Stats) _stats[s.Id] = s;
        }

        public void LinkItem(ItemDefinition item)
        {
            if (item != null && !_items.Contains(item)) _items.Add(item);
        }

        public void UnlinkItem(ItemDefinition item) => _items.Remove(item);

        /// Canonical StatsForge pipeline — see docs section 8.
        public float GetStat(string statId)
        {
            if (!_stats.TryGetValue(statId, out var stat)) return 0f;

            float flat = 0f, percent = 0f, mult = 1f;

            AccumulateClass(Data.Modifiers, statId, ref flat, ref percent, ref mult);

            foreach (var item in _items)
                AccumulateDef(item.Modifiers, statId, null, ref flat, ref percent, ref mult);

            if (Effects != null)
                foreach (var active in Effects.Active)
                {
                    if (active.Definition.Type != "modifier") continue;
                    AccumulateDef(active.Definition.Modifiers, statId, active,
                                  ref flat, ref percent, ref mult);
                }

            float effectiveBase = stat.BaseValue + Level * stat.Growth;
            float raw = (effectiveBase + flat) * (1f + percent / 100f) * mult;
            return Mathf.Clamp(raw, stat.Min, stat.Max);
        }

        static void AccumulateClass(List<Modifier> mods, string statId,
                                    ref float flat, ref float percent, ref float mult)
        {
            if (mods == null) return;
            foreach (var m in mods)
            {
                if (!m.Active || m.Target != statId) continue;
                switch (m.Operation)
                {
                    case "add":      flat    += m.Value; break;
                    case "subtract": flat    -= m.Value; break;
                    case "percent":  percent += m.Value; break;
                    case "multiply": mult    *= m.Value; break;
                }
            }
        }

        static void AccumulateDef(List<DefModifier> mods, string statId, ActiveEffect source,
                                  ref float flat, ref float percent, ref float mult)
        {
            if (mods == null) return;
            foreach (var m in mods)
            {
                if (!m.Active || m.Stat != statId) continue;
                var value = source != null ? source.ValueFor(m) : m.Value;
                switch (m.Type)
                {
                    case "flat":           flat    += value; break;
                    case "percentage":     percent += value; break;
                    case "multiplicative": mult    *= value; break;
                }
            }
        }
    }
}
Classes + Items — step by step

Classes + Items — step by step

Add this on top of the classes-only setup when you want weapons, armor or accessories to mutate a class's stats at runtime.

File:stats_forge/data/knight.json (bundle)
JSON
{
  "entity": {
    "id": "knight",
    "name": "Knight",
    "stats": [
      { "id": "damage", "baseValue": 18, "min": 0, "max": 400, "growth": 2 }
    ],
    "modifiers": [],
    "items": [
      { "itemId": "iron_sword", "equipped": true },
      { "itemId": "kite_shield", "equipped": true }
    ],
    "skills": []
  },
  "itemDefinitions": [
    {
      "id": "iron_sword", "name": "Iron Sword", "category": "weapon",
      "modifiers": [
        { "stat": "damage", "type": "flat", "value": 8, "name": "Sharp Edge" }
      ]
    },
    {
      "id": "kite_shield", "name": "Kite Shield", "category": "armor",
      "modifiers": [
        { "stat": "defense", "type": "percentage", "value": 15 }
      ],
      "effects": [
        { "effectId": "shield_wall", "target": "self", "trigger": "on_equip" }
      ]
    }
  ]
}

Resolving entity.items[].itemId → itemDefinitions

File:Assets/Resources/StatsForge/Scripts/Data/ItemDefinition.cs
C#
using System.Collections.Generic;
using Newtonsoft.Json;

namespace StatsForge.Data
{
    /// Modifier shape used inside item and effect definitions.
    public sealed class DefModifier
    {
        [JsonProperty("stat")]      public string Stat    { get; set; }
        [JsonProperty("type")]      public string Type    { get; set; } // flat | percentage | multiplicative
        [JsonProperty("value")]     public float  Value   { get; set; }
        [JsonProperty("name")]      public string Name    { get; set; }
        [JsonProperty("active")]    public bool   Active  { get; set; } = true;
        [JsonProperty("applyOn")]   public string ApplyOn { get; set; } // instant | tick | expire
        [JsonProperty("condition")] public ModifierCondition Condition { get; set; }
    }

    /// Reference to a reusable effect, used by items and skills alike.
    public sealed class EffectRef
    {
        [JsonProperty("effectId")]  public string          EffectId  { get; set; }
        [JsonProperty("target")]    public string          Target    { get; set; } // self | target
        [JsonProperty("trigger")]   public string          Trigger   { get; set; }
        [JsonProperty("overrides")] public EffectOverrides Overrides { get; set; }
    }

    public sealed class ItemDefinition
    {
        [JsonProperty("id")]        public string            Id        { get; set; }
        [JsonProperty("name")]      public string            Name      { get; set; }
        [JsonProperty("category")]  public string            Category  { get; set; } // weapon | armor | accessory | consumable
        [JsonProperty("modifiers")] public List<DefModifier> Modifiers { get; set; } = new();
        [JsonProperty("effects")]   public List<EffectRef>   Effects   { get; set; } = new();
    }

    /// Top-level export envelope.
    public sealed class EntityBundle
    {
        [JsonProperty("entity")]            public EntityData            Entity            { get; set; }
        [JsonProperty("itemDefinitions")]   public List<ItemDefinition>   ItemDefinitions   { get; set; } = new();
        [JsonProperty("effectDefinitions")] public List<EffectDefinition> EffectDefinitions { get; set; } = new();
        [JsonProperty("skillDefinitions")]  public List<SkillDefinition>  SkillDefinitions  { get; set; } = new();
    }
}
File:Assets/Resources/StatsForge/Scripts/Gameplay/KnightSpawner.cs
C#
using UnityEngine;
using StatsForge.Data;
using StatsForge.Gameplay;

public class KnightSpawner : MonoBehaviour
{
    void Start()
    {
        var bundle = EntityLoader.Load("knight");
        if (bundle == null) return;

        var go     = new GameObject(bundle.Entity.Name);
        var runner = go.AddComponent<EffectRunner>();
        var caster = go.AddComponent<SkillCaster>();
        var knight = go.AddComponent<CharacterClass>();

        knight.Data    = bundle.Entity;
        knight.Level   = 1;
        knight.Effects = runner;

        // entity.items[].itemId → itemDefinitions
        foreach (var reference in bundle.Entity.Items)
            if (reference.Equipped && bundle.Items.TryGetValue(reference.Id, out var item))
                knight.LinkItem(item);

        // entity.skills[].skillId → skillDefinitions
        caster.SelfEffects = runner;
        caster.Bind(bundle.Effects.Values);
        foreach (var reference in bundle.Entity.Skills)
            if (bundle.Skills.TryGetValue(reference.Id, out var skill))
                Debug.Log($"Ready skill: {skill.Name}");

        Debug.Log($"Damage with loadout: {knight.GetStat(\"damage\")}");
    }
}

Linking items at runtime

Static loadout

Items baked in at load time — matches the StatsForge export exactly. Best for enemies, bosses, and preset character classes.

Dynamic equip / unequip

Call LinkItem(item) / UnlinkItem(item) at runtime and re-query GetStat(). StatsForge does not model equipment slots — that is your engine's responsibility.

Effects — step by step

Effects — step by step

effectDefinitions hold reusable effects referenced by items and skills. A reference is { effectId, target, trigger, overrides? }: the definition says what happens, the reference says who receives it and when.

File:stats_forge/data/knight.json → effectDefinitions
JSON
"effectDefinitions": [
  {
    "id": "shield_wall",
    "name": "Shield Wall",
    "type": "modifier",
    "category": "buff",
    "duration": { "type": "timed", "value": 5 },
    "stacking": { "enabled": true, "maxStacks": 3, "behavior": "refresh" },
    "modifiers": [
      { "stat": "defense", "type": "percentage", "value": 50, "applyOn": "instant" }
    ]
  },
  {
    "id": "burn",
    "name": "Burn",
    "type": "gameplay",
    "category": "dot",
    "duration": { "type": "timed", "value": 6 },
    "tickRate": 1,
    "gameplay": {
      "action": "damage", "targetStat": "health",
      "operation": "flat", "value": 12, "applyOn": "tick"
    }
  }
]

Two kinds of effect

  • type: "modifier" — carries modifiers[] that enter the stat pipeline while the effect is active.
  • type: "gameplay" — carries gameplay { action: damage | heal, targetStat, operation, value }. It changes the current value of a stat (e.g. current health); it never changes the base stat.
  • duration is { type: "instant" | "timed" | "permanent", value? }. Only timed effects use tickRate; instant effects never tick.
  • stacking is optional. When absent, treat the effect as single-instance (refresh on reapply).
  • overrides on a reference may replace duration, tickRate, stacking and modifierValues (keyed by stat id). Apply them on top of the definition without mutating it.

1 · Effect models

Mirror the definition shape exactly, including the nested duration object.

File:Assets/Resources/StatsForge/Scripts/Data/EffectDefinition.cs
C#
using System.Collections.Generic;
using Newtonsoft.Json;

namespace StatsForge.Data
{
    public sealed class EffectDuration
    {
        [JsonProperty("type")]  public string Type  { get; set; } // instant | timed | permanent
        [JsonProperty("value")] public float  Value { get; set; } // seconds, timed only
    }

    public sealed class EffectStacking
    {
        [JsonProperty("enabled")]   public bool   Enabled   { get; set; }
        [JsonProperty("maxStacks")] public int    MaxStacks { get; set; } = 1;
        [JsonProperty("behavior")]  public string Behavior  { get; set; } // refresh | independent | ignore
    }

    public sealed class GameplayPayload
    {
        [JsonProperty("action")]     public string Action     { get; set; } // damage | heal
        [JsonProperty("targetStat")] public string TargetStat { get; set; }
        [JsonProperty("operation")]  public string Operation  { get; set; } // flat | percentage
        [JsonProperty("value")]      public float  Value      { get; set; }
        [JsonProperty("applyOn")]    public string ApplyOn    { get; set; } // instant | tick | expire
    }

    public sealed class EffectOverrides
    {
        [JsonProperty("duration")]        public float?                     Duration       { get; set; }
        [JsonProperty("tickRate")]        public float?                     TickRate       { get; set; }
        [JsonProperty("stacking")]        public EffectStacking             Stacking       { get; set; }
        [JsonProperty("modifierValues")]  public Dictionary<string, float>  ModifierValues { get; set; }
    }

    public sealed class EffectDefinition
    {
        [JsonProperty("id")]        public string            Id        { get; set; }
        [JsonProperty("name")]      public string            Name      { get; set; }
        [JsonProperty("type")]      public string            Type      { get; set; } // modifier | gameplay
        [JsonProperty("category")]  public string            Category  { get; set; } // buff | debuff | dot | hot | cc ...
        [JsonProperty("duration")]  public EffectDuration    Duration  { get; set; }
        [JsonProperty("tickRate")]  public float             TickRate  { get; set; }
        [JsonProperty("stacking")]  public EffectStacking    Stacking  { get; set; }
        [JsonProperty("modifiers")] public List<DefModifier> Modifiers { get; set; } = new();
        [JsonProperty("gameplay")]  public GameplayPayload   Gameplay  { get; set; }

        public bool IsInstant   => Duration?.Type == "instant";
        public bool CanTick     => Duration?.Type == "timed" && TickRate > 0f;
    }
}

2 · Applying effects at runtime

Keep active modifier effects in a list per entity, feed them into the same stat pipeline, and resolve gameplay effects against current values.

File:Assets/Resources/StatsForge/Scripts/Gameplay/EffectRunner.cs
C#
using System.Collections.Generic;
using UnityEngine;

namespace StatsForge.Gameplay
{
    using StatsForge.Data;

    /// Your own health / mana pool. StatsForge describes intent, not storage.
    public interface IStatPool
    {
        float GetCurrent(string statId);
        void  ModifyCurrent(string statId, float value, string operation); // flat | percentage
    }

    /// One live instance of an effect on an entity.
    public sealed class ActiveEffect
    {
        public EffectDefinition Definition;
        public EffectOverrides  Overrides;
        public float            Remaining;
        public float            TickClock;
        public int              Stacks = 1;

        public float DurationSeconds => Overrides?.Duration ?? Definition.Duration?.Value ?? 0f;
        public float TickRate        => Overrides?.TickRate ?? Definition.TickRate;

        /// Definition value with per-application overrides applied (never mutates the definition).
        public float ValueFor(DefModifier m)
        {
            if (Overrides?.ModifierValues != null &&
                Overrides.ModifierValues.TryGetValue(m.Stat, out var v)) return v;
            return m.Value;
        }
    }

    public sealed class EffectRunner : MonoBehaviour
    {
        readonly List<ActiveEffect> _active = new();

        public IReadOnlyList<ActiveEffect> Active => _active;

        public void Apply(EffectDefinition def, EffectOverrides ov = null)
        {
            if (def == null) return;

            var isInstant = def.Duration?.Type == "instant";

            // Gameplay effects change CURRENT values; they never enter the stat pipeline.
            if (def.Type == "gameplay" && (isInstant || def.Gameplay?.ApplyOn == "instant"))
                ResolveGameplay(def, ov);

            if (isInstant) return; // nothing to keep alive, and instant effects never tick

            var existing = _active.Find(a => a.Definition.Id == def.Id);
            if (existing != null)
            {
                if (def.Stacking is { Enabled: true })
                    existing.Stacks = Mathf.Min(existing.Stacks + 1, def.Stacking.MaxStacks);
                existing.Remaining = existing.DurationSeconds; // refresh
                return;
            }

            var instance = new ActiveEffect { Definition = def, Overrides = ov };
            instance.Remaining = def.Duration?.Type == "timed"
                ? instance.DurationSeconds
                : float.PositiveInfinity; // permanent
            _active.Add(instance);
        }

        void Update()
        {
            var dt = Time.deltaTime;

            for (int i = _active.Count - 1; i >= 0; i--)
            {
                var a = _active[i];

                if (a.TickRate > 0f)
                {
                    a.TickClock += dt;
                    while (a.TickClock >= a.TickRate)
                    {
                        a.TickClock -= a.TickRate;
                        ResolveGameplay(a.Definition, a.Overrides);
                    }
                }

                if (float.IsPositiveInfinity(a.Remaining)) continue; // permanent
                a.Remaining -= dt;
                if (a.Remaining <= 0f) _active.RemoveAt(i);
            }
        }

        void ResolveGameplay(EffectDefinition def, EffectOverrides ov)
        {
            var g = def.Gameplay;
            if (g == null) return;
            var signed = g.Action == "heal" ? g.Value : -g.Value;
            GetComponent<IStatPool>()?.ModifyCurrent(g.TargetStat, signed, g.Operation);
        }
    }
}
Skills — step by step

Skills — step by step

skillDefinitions describe how an action is used: cost, cooldown, castTime, targeting, and the effect applications it triggers. Skills never duplicate effect data — they reference effectId.

File:stats_forge/data/knight.json → skillDefinitions
JSON
"entity": {
  "skills": [{ "skillId": "fireball" }]
},
"skillDefinitions": [
  {
    "id": "fireball",
    "name": "Fireball",
    "description": "Hurls a burning sphere.",
    "cost": { "stat": "mana", "value": 20 },
    "cooldown": 5,
    "castTime": 0.6,
    "targeting": { "type": "target" },
    "effects": [
      { "effectId": "burn", "target": "target", "trigger": "on_cast" },
      { "effectId": "shield_wall", "target": "self", "trigger": "on_cast",
        "overrides": { "duration": 3, "modifierValues": { "defense": 25 } } }
    ]
  }
]

targeting.type is self, target, area or none. Each effect application can override it with its own target field.

1 · Skill models

cost is { stat, value } and may be absent. effects[] uses the same reference shape as items.

File:Assets/Resources/StatsForge/Scripts/Data/SkillDefinition.cs
C#
using System.Collections.Generic;
using Newtonsoft.Json;

namespace StatsForge.Data
{
    public sealed class SkillCost
    {
        [JsonProperty("stat")]  public string Stat  { get; set; }
        [JsonProperty("value")] public float  Value { get; set; }
    }

    public sealed class SkillTargeting
    {
        [JsonProperty("type")] public string Type { get; set; } // self | target | area | none
    }

    public sealed class SkillDefinition
    {
        [JsonProperty("id")]          public string          Id          { get; set; }
        [JsonProperty("name")]        public string          Name        { get; set; }
        [JsonProperty("description")] public string          Description { get; set; }
        [JsonProperty("cost")]        public SkillCost       Cost        { get; set; }
        [JsonProperty("cooldown")]    public float           Cooldown    { get; set; }
        [JsonProperty("castTime")]    public float           CastTime    { get; set; }
        [JsonProperty("targeting")]   public SkillTargeting  Targeting   { get; set; }
        [JsonProperty("effects")]     public List<EffectRef> Effects     { get; set; } = new();
    }
}

2 · Casting a skill

Check cooldown, pay the cost from the current stat value, wait castTime, then apply each referenced effect to the resolved target.

File:Assets/Resources/StatsForge/Scripts/Gameplay/SkillCaster.cs
C#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace StatsForge.Gameplay
{
    using StatsForge.Data;

    public sealed class SkillCaster : MonoBehaviour
    {
        public EffectRunner SelfEffects;

        readonly Dictionary<string, float> _readyAt = new();
        Dictionary<string, EffectDefinition> _effects;

        public void Bind(IEnumerable<EffectDefinition> effectDefinitions)
        {
            _effects = new Dictionary<string, EffectDefinition>();
            foreach (var e in effectDefinitions) _effects[e.Id] = e;
        }

        public bool CanCast(SkillDefinition skill, IStatPool pool)
        {
            if (_readyAt.TryGetValue(skill.Id, out var t) && Time.time < t) return false;
            return skill.Cost == null || pool.GetCurrent(skill.Cost.Stat) >= skill.Cost.Value;
        }

        public void Cast(SkillDefinition skill, IStatPool pool, EffectRunner targetEffects)
        {
            if (!CanCast(skill, pool)) return;

            if (skill.Cost != null) pool.ModifyCurrent(skill.Cost.Stat, -skill.Cost.Value, "flat");
            _readyAt[skill.Id] = Time.time + skill.Cooldown;
            StartCoroutine(CastRoutine(skill, targetEffects));
        }

        IEnumerator CastRoutine(SkillDefinition skill, EffectRunner targetEffects)
        {
            if (skill.CastTime > 0f) yield return new WaitForSeconds(skill.CastTime);

            foreach (var app in skill.Effects)
            {
                if (!_effects.TryGetValue(app.EffectId, out var def)) continue;
                // The application decides WHO receives it; the definition decides WHAT happens.
                var runner = app.Target == "target" ? targetEffects : SelfEffects;
                runner?.Apply(def, app.Overrides);
            }
        }
    }
}
Regeneration

Regeneration

Resource stats can carry an optional "regen" block. It only appears when the designer enabled it, so treat a missing block as "no regeneration".

"flat" adds value points per second; "percent" adds value % of the stat's max per second.

File:stats_forge/data/knight.json → entity.stats[].regen
JSON
"stats": [
  { "id": "health",  "baseValue": 120, "min": 0, "max": 999, "growth": 12,
    "regen": { "type": "flat", "value": 2.5 } },
  { "id": "mana",    "baseValue": 60,  "min": 0, "max": 500, "growth": 5,
    "regen": { "type": "percent", "value": 2 } },
  { "id": "defense", "baseValue": 10,  "min": 0, "max": 200, "growth": 1 }
]

Runtime tick

Keep the current pool separate from the calculated max: tick regeneration each frame and clamp to the final stat value.

File:Assets/Resources/StatsForge/Scripts/Gameplay/StatPool.cs
C#
using UnityEngine;
using StatsForge.Data;

namespace StatsForge.Gameplay
{
    /// Ticks the optional "regen" block of a stat and clamps to its max.
    public sealed class StatPool : MonoBehaviour
    {
        private StatData definition;   // from the loaded entity
        private float max;             // final value from CharacterClass
        public float Current { get; private set; }

        public void Setup(StatData definition, float maxValue)
        {
            this.definition = definition;
            max = maxValue;
            Current = maxValue;
        }

        private void Update()
        {
            var regen = definition?.Regen;
            if (regen == null) return;   // regeneration disabled for this stat

            float perSecond = regen.Type == "percent" ? max * regen.Value / 100f : regen.Value;
            Current = Mathf.Min(Current + perSecond * Time.deltaTime, max);
        }
    }
}
Calculation order (canonical)

Calculation order (canonical)

Apply this pipeline per stat. Treat debuff and weakness percent values as negative.

Pseudocode
1. effectiveBase = baseValue + level * growth
2. flatSum     = Σ add − Σ subtract        (class modifiers)
               + Σ flat                    (item + active effect modifiers)
3. percentSum  = Σ percent                 (class) + Σ percentage (items + effects)
                                           (debuff / weakness counted as negative)
4. multiplier  = Π multiply                (class) × Π multiplicative (items + effects)
5. final = clamp(
       (effectiveBase + flatSum) * (1 + percentSum / 100) * multiplier,
       min, max
   )

Gameplay effects (damage / heal) are NOT part of this pipeline:
they change CURRENT pools (health, mana) after the final value is known.
  • Simple: skip the modifier loop entirely if stats[].modifiers is empty AND the entity has no items — return effectiveBase clamped.
  • Intermediate: implement only add and percent operations; ignore multiply until you need it.
  • Advanced / Custom: implement all operations plus the condition field. Treat unknown condition types as 'always' to stay forward-compatible.
Best practices

Recommended workflow

  • One JSON file per entity — easy to diff, version, and share.
  • Use IDs for gameplay references (lookup by id, never by index).
  • Keep balance data outside source code — designers can iterate without rebuilding.
  • Load stats before modifiers so modifier targets always resolve.
  • Use StatsForge as the single source of truth for game balance.
Supported systems

What you can model

Character Classes

Enemies

Equipment

Buffs & Debuffs

Status Effects

Progression Systems

Skills & Effects

Coming soon

Loot Tables

Coming soon

Back to documentation

← All docs