Unity Achievement System With ScriptableObjects and Events

Illustration: a gold trophy badge popping up with stars

Achievements give players goals beyond the main game and cost very little to build. The hard part is structure: if every achievement is hard-coded into enemy, coin and level scripts, you end up with a tangle that is painful to extend. This guide builds a Unity achievement system with ScriptableObject definitions, progress counters, a small event hook so gameplay scripts stay clean, an unlock popup and saved progress.

The Design

Three pieces keep this clean:

  • AchievementData (ScriptableObject): the definition. Name, description, icon, a stat key and a goal number. One asset per achievement, edited in the Inspector.
  • AchievementManager: tracks progress per achievement, unlocks when the goal is reached, saves and loads.
  • A static event that gameplay code calls, like Achievements.Report("enemies_killed"). Enemies and pickups know nothing about specific achievements.

Counting by a stat key is the trick. Several achievements can share one stat: “Kill 10 enemies” and “Kill 100 enemies” both listen to enemies_killed, so you add one line of reporting code, not two. If the ScriptableObject pattern is new, read the ScriptableObjects guide first. The same data-driven idea powers the quest system.

Achievement Definitions

using UnityEngine;

[CreateAssetMenu(menuName = "Achievements/Achievement")]
public class AchievementData : ScriptableObject
{
    [Tooltip("Unique and never changed once released, used for saving")]
    public string id;
    public string title;
    [TextArea] public string description;
    public Sprite icon;

    [Tooltip("The stat this achievement counts")]
    public string statKey;
    [Min(1)] public int goal = 1;
    public bool hidden;
}

Create assets with Assets > Create > Achievements > Achievement. Give each a permanent id. Do not use the asset name or title for saving, because renaming them later would wipe players’ progress.

The Achievement Manager

using System;
using System.Collections.Generic;
using UnityEngine;

public static class Achievements
{
    // gameplay code calls this
    public static void Report(string statKey, int amount = 1)
        => OnStat?.Invoke(statKey, amount);

    public static event Action<string, int> OnStat;
    public static event Action<AchievementData> OnUnlocked;

    internal static void RaiseUnlocked(AchievementData a) => OnUnlocked?.Invoke(a);
}

public class AchievementManager : MonoBehaviour
{
    [SerializeField] List<AchievementData> all = new();

    readonly Dictionary<string, int> stats = new();
    readonly HashSet<string> unlocked = new();

    void OnEnable() => Achievements.OnStat += HandleStat;
    void OnDisable() => Achievements.OnStat -= HandleStat;

    void HandleStat(string key, int amount)
    {
        stats.TryGetValue(key, out int current);
        current += amount;
        stats[key] = current;

        foreach (var a in all)
        {
            if (a.statKey != key || unlocked.Contains(a.id)) continue;
            if (current >= a.goal)
            {
                unlocked.Add(a.id);
                Achievements.RaiseUnlocked(a);
                Save();
            }
        }
    }

    public int GetProgress(AchievementData a)
    {
        stats.TryGetValue(a.statKey, out int v);
        return Mathf.Min(v, a.goal);
    }

    public bool IsUnlocked(AchievementData a) => unlocked.Contains(a.id);

    // Save/Load are shown in the saving section
    void Save() { }
}

The manager lives in your first scene. If it needs to survive scene loads, put it on a persistent object; the singleton patterns guide covers doing that without creating duplicates. Subscribing in OnEnable and unsubscribing in OnDisable matters. Static events outlive scenes, so a missed unsubscribe leaves a handler pointing at a destroyed object. For a refresher on how events work, see the events and delegates guide.

Note that stats are stored by key, separate from achievements. That means a new achievement added in an update can unlock immediately for players who already passed the goal, because the stat total is already saved.

Hooking Up Gameplay Events

Gameplay scripts only report facts:

// in your enemy's death method
Achievements.Report("enemies_killed");

// in your coin pickup
Achievements.Report("coins_collected", value);

// when a level is finished
Achievements.Report("levels_completed");

// one-time moments
Achievements.Report("found_secret_room");

That is all the coupling there is. A one-time achievement is just a goal of 1. You can add or remove achievements without editing a single gameplay script, as long as the stat key already exists. For things like “finish a level without taking damage”, report the stat only when that condition is true, at the moment the level ends.

A toast that slides in, waits and fades out. Queue them, because two achievements can unlock on the same frame.

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class AchievementPopup : MonoBehaviour
{
    [SerializeField] CanvasGroup group;
    [SerializeField] TMP_Text titleText;
    [SerializeField] TMP_Text descText;
    [SerializeField] Image iconImage;
    [SerializeField] float showTime = 3f;
    [SerializeField] float fadeTime = 0.4f;

    readonly Queue<AchievementData> queue = new();
    bool showing;

    void Awake() => group.alpha = 0f;
    void OnEnable() => Achievements.OnUnlocked += Enqueue;
    void OnDisable() => Achievements.OnUnlocked -= Enqueue;

    void Enqueue(AchievementData a)
    {
        queue.Enqueue(a);
        if (!showing) StartCoroutine(Run());
    }

    IEnumerator Run()
    {
        showing = true;
        while (queue.Count > 0)
        {
            var a = queue.Dequeue();
            titleText.text = a.title;
            descText.text = a.description;
            iconImage.sprite = a.icon;

            yield return Fade(0f, 1f);
            yield return new WaitForSecondsRealtime(showTime);
            yield return Fade(1f, 0f);
        }
        showing = false;
    }

    IEnumerator Fade(float from, float to)
    {
        for (float t = 0f; t < fadeTime; t += Time.unscaledDeltaTime)
        {
            group.alpha = Mathf.Lerp(from, to, t / fadeTime);
            yield return null;
        }
        group.alpha = to;
    }
}

Use unscaled time so the popup still works if the game is paused or in slow motion. Put the popup on a Canvas with a CanvasGroup and set that group’s Interactable and Blocks Raycasts off so it never blocks clicks. Add a sound effect in Run for a satisfying unlock. For the text setup, see the TextMeshPro tutorial.

Saving Progress

Unity’s JsonUtility cannot serialize dictionaries, so convert to lists. Add this to the manager:

[Serializable]
class SaveData
{
    public List<string> statKeys = new();
    public List<int> statValues = new();
    public List<string> unlockedIds = new();
}

string SavePath => System.IO.Path.Combine(Application.persistentDataPath, "achievements.json");

void Save()
{
    var data = new SaveData();
    foreach (var kv in stats) { data.statKeys.Add(kv.Key); data.statValues.Add(kv.Value); }
    data.unlockedIds.AddRange(unlocked);
    System.IO.File.WriteAllText(SavePath, JsonUtility.ToJson(data));
}

void Awake()
{
    if (!System.IO.File.Exists(SavePath)) return;
    var data = JsonUtility.FromJson<SaveData>(System.IO.File.ReadAllText(SavePath));
    for (int i = 0; i < data.statKeys.Count; i++) stats[data.statKeys[i]] = data.statValues[i];
    foreach (var id in data.unlockedIds) unlocked.Add(id);
}

Remove the empty Save() stub from earlier when you add this. Saving after each unlock is cheap. Saving stats on every kill is wasteful, so also save on scene change and when the application pauses or quits. The save system guide goes into file locations and error handling in depth.

Extending It

  • Achievements screen: loop over the all list, show the icon and a progress bar from GetProgress, and gray out locked ones. Hide titles for achievements with hidden set until unlocked.
  • Platform integration: Steam and console achievements have their own APIs. Keep your system as the source of truth and call the platform API from the OnUnlocked event.
  • Max-style stats: for “reach combo 20”, add a second report method that stores the highest value instead of adding.
  • Progress bars: expose the goal and current value so a UI row can show 7/10 style progress with a Slider or Image fill.
  • Reset button: delete the save file and clear both collections, handy for testing.

📚 Design better goals

Good achievements come from good game design. Our list of programming and game design books includes titles on player motivation and progression.

Troubleshooting

Achievement never unlocks

The statKey on the asset does not exactly match the string reported in code. Keys are case-sensitive. Also check that the achievement is in the manager’s list.

Achievement unlocks twice

Two managers exist in the scene, or the manager was duplicated by a scene reload. Make sure only one instance runs.

NullReferenceException in the popup

One of the serialized fields (group, text or icon) is not assigned. Also, an achievement without an icon leaves the Image with a null sprite, which shows a white box; hide the image if the sprite is null.

Progress resets every time the game starts

Nothing is loaded in Awake, or the save file path changes. Log Application.persistentDataPath and confirm the file exists after a save.

Popup does not appear while the game is paused

The popup uses scaled time. Use WaitForSecondsRealtime and Time.unscaledDeltaTime as shown.

Events fire after changing scenes with errors

A static event still holds a handler from a destroyed object. Unsubscribe in OnDisable or OnDestroy.

Achievements fire during loading or in the main menu

Gameplay code is reporting stats at the wrong time, for example enemies being destroyed when a scene unloads. Report only from real gameplay events, not from OnDestroy.

Stats go up but the achievement is already unlocked

That is expected. Once the id is in the unlocked set the manager skips it, so the popup never repeats. Keep counting the stat anyway, since other achievements may use it.

FAQ

Why use ScriptableObjects instead of a big list in code?

Designers can add and tweak achievements in the Inspector without touching code, and each one can hold an icon and text directly.

Should achievements be saved with the main save file?

Usually not. Achievements are account-wide, while save slots belong to individual runs. A separate file keeps them intact when a player deletes a slot.

How do I stop players from editing the save to cheat?

You can’t fully prevent it for a local file. For single-player games it is usually fine to ignore. Platform achievements validate on the server side if that matters.

Can I trigger an achievement from a UnityEvent?

Yes. Add a small component with a public method that calls Achievements.Report, then wire it up in the Inspector for things like entering a trigger zone.

How many achievements should a small game have?

10 to 30 is plenty. Make most of them reachable by playing normally, with a few hard ones for completionists.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *