Dirty Flag
Dirty Flag
Section titled “Dirty Flag”One-line pattern summary
Section titled “One-line pattern summary”A lazy update pattern that marks expensive calculations so they are recomputed only when the underlying value changes.
Typical Unity use cases
Section titled “Typical Unity use cases”- When stat aggregation or layout calculation is expensive.
- When recalculating every frame is unnecessary.
Parts (roles)
Section titled “Parts (roles)”- Primary Data: source data
- Dirty Flag: whether recalculation is needed
- Cache: computed result
Unity example (C#)
Section titled “Unity example (C#)”The code below is a simplified Unity example based on the scenario described above.
public sealed class PlayerAttackStat{ private int baseAttackPower; private int equipmentBonusPower; private bool needsRecalculation = true; private int cachedAttackPower;
public void SetBaseAttackPower(int value) { baseAttackPower = value; needsRecalculation = true; }
public void SetEquipmentBonusPower(int value) { equipmentBonusPower = value; needsRecalculation = true; }
public int GetFinalAttackPower() { if (!needsRecalculation) { return cachedAttackPower; }
cachedAttackPower = baseAttackPower + equipmentBonusPower; needsRecalculation = false; return cachedAttackPower; }}Advantages
Section titled “Advantages”- It reduces unnecessary work per frame by calculating only when the value actually changes.
- It is especially effective for values that do not change often, such as UI, stats, or transforms.
Things to watch out for
Section titled “Things to watch out for”- If the flag update is missed, bugs appear where stale data is used.
- When dependencies become complex, it becomes difficult to track which change should set the flag.
Interaction diagram
Section titled “Interaction diagram”This shows the lazy update flow where recalculation happens only when a value changes.