quot;progress_{slot}.json"); public static void Load(int slot = 0) { Slot = slot; string path = PathFor(slot); try { Data = File.Exists(path) ? JsonUtility.FromJson<ProgressData>(File.ReadAllText(path)) ?? new ProgressData() : new ProgressData(); } catch (Exception e) { Debug.LogError(quot;[ProgressStore] Could not read {path}: {e.Message}. Starting fresh (old file kept as .bad)."); try { File.Copy(path, path + ".bad", true); } catch { /* best effort */ } Data = new ProgressData(); } IsDirty = false; IsLoaded = true; } public static void MarkDirty() => IsDirty = true; /// <summary>Writes only if something changed (Dirty Flag pattern).</summary> public static void SaveIfDirty() { if (!IsDirty) return; string path = PathFor(Slot); string tmp = path + ".tmp"; try { File.WriteAllText(tmp, JsonUtility.ToJson(Data, true)); if (File.Exists(path)) File.Replace(tmp, path, path + ".bak"); else File.Move(tmp, path); IsDirty = false; } catch (Exception e) { Debug.LogError(quot;[ProgressStore] Save failed: {e.Message}"); } } public static void DeleteSlot(int slot) { string path = PathFor(slot); if (File.Exists(path)) File.Delete(path); if (slot == Slot) { Data = new ProgressData(); IsDirty = false; } } // ---------- counter helpers ---------- public static int GetCounter(string key) { foreach (var c in Data.counters) if (c.key == key) return c.value; return 0; } public static int AddToCounter(string key, int amount) { for (int i = 0; i < Data.counters.Count; i++) { if (Data.counters[i].key != key) continue; var c = Data.counters[i]; c.value += amount; Data.counters[i] = c; // struct in a list: write it back MarkDirty(); return c.value; } Data.counters.Add(new CounterEntry { key = key, value = amount }); MarkDirty(); return amount; } } } ``` **Why these choices** - **`JsonUtility`** is built in, fast and allocation-light, but cannot serialise `Dictionary` or `HashSet`; hence lists and a `CounterEntry` struct. The runtime keeps a `HashSet` for lookups (below) and only the list is saved. - **Temp file + `File.Replace`** makes the swap close to atomic on desktop file systems and keeps a `.bak`. `File.Replace` is a .NET API; behaviour on every console or mobile file system was **not verified** - on those platforms use the vendor save API. - **`.bad` copy on read failure** means a corrupt file never silently erases a student's progress; you can inspect it. - This is deliberately smaller than the save system in [[High Scores, Saves and Player Stats]]. If you already use that `SaveSystem`, store `ProgressData` as one of its sections instead of a separate file. ## 4.3 `CollectibleLedger.cs` ```csharp using System; using System.Collections.Generic; using UnityEngine; namespace PowerUps { /// <summary> /// Remembers which souvenirs are found (per save) and how many exist per level (per session). /// Put on a persistent bootstrap object. /// </summary> [DefaultExecutionOrder(-50)] public sealed class CollectibleLedger : MonoBehaviour { public static CollectibleLedger Instance { get; private set; } [SerializeField] int saveSlot = 0; [Tooltip("Save immediately on every collect (simple, safe) or only at checkpoints/quit.")] [SerializeField] bool saveOnCollect = true; readonly HashSet<string> _found = new(); readonly Dictionary<string, HashSet<string>> _knownPerLevel = new(); // levelId -> collectible ids seen this session /// <summary>(levelId, collectibleId, foundInLevel, knownInLevel)</summary> public event Action<string, string, int, int> CollectibleFound; void Awake() { if (Instance != null && Instance != this) { Destroy(gameObject); return; } Instance = this; DontDestroyOnLoad(gameObject); ProgressStore.EnsureLoaded(saveSlot); foreach (var key in ProgressStore.Data.collectibles) _found.Add(key); } void OnApplicationPause(bool paused) { if (paused) ProgressStore.SaveIfDirty(); } void OnApplicationQuit() => ProgressStore.SaveIfDirty(); static string Key(string levelId, string id) => levelId + "/" + id; public bool IsFound(string levelId, string id) => _found.Contains(Key(levelId, id)); /// <summary>Collectibles call this on enable so the ledger knows the level's total.</summary> public void Register(string levelId, string id) { if (!_knownPerLevel.TryGetValue(levelId, out var set)) _knownPerLevel[levelId] = set = new HashSet<string>(); set.Add(id); } public void MarkFound(string levelId, string id) { if (!_found.Add(Key(levelId, id))) return; // already had it ProgressStore.Data.collectibles.Add(Key(levelId, id)); ProgressStore.AddToCounter("collectibles.total", 1); ProgressStore.AddToCounter("collectibles." + levelId, 1); if (saveOnCollect) ProgressStore.SaveIfDirty(); CollectibleFound?.Invoke(levelId, id, FoundIn(levelId), KnownIn(levelId)); UnlockService.Instance?.NotifyProgressChanged(); } public int FoundIn(string levelId) { string prefix = levelId + "/"; int n = 0; foreach (var k in _found) if (k.StartsWith(prefix, StringComparison.Ordinal)) n++; return n; } /// <summary>Total placed in the level, as far as this session has seen (load the level once to know).</summary> public int KnownIn(string levelId) => _knownPerLevel.TryGetValue(levelId, out var s) ? s.Count : 0; } } ``` > [!tip] Totals for levels you have not loaded > `KnownIn` only knows levels that have been loaded this session. For a level-select screen that shows "3 / 10" for every level, bake totals into a `LevelCatalog` asset with an Editor script (exercise 2), or write them by hand in the beat chart. ## 4.4 `Collectible.cs` ```csharp using UnityEngine; namespace PowerUps { /// <summary> /// Marks a placed PowerPickup as a one-time souvenir with a stable ID. /// If already found in this save, it is shown as a "ghost" (or hidden). /// </summary> [RequireComponent(typeof(PowerPickup))] public sealed class Collectible : MonoBehaviour { [Tooltip("Generated automatically. Do not edit by hand; use the validator if duplicates appear.")] [SerializeField] string id; [Tooltip("Empty = scene name. Set explicitly if one level spans several scenes.")] [SerializeField] string levelIdOverride; [Header("Already-found presentation")] [SerializeField] bool hideIfFound = false; [SerializeField] GameObject ghostVisual; // a translucent version, still collectable for feel but worth nothing public string Id => id; public string LevelId => string.IsNullOrEmpty(levelIdOverride) ? gameObject.scene.name : levelIdOverride; PowerPickup _pickup; void Reset() => id = System.Guid.NewGuid().ToString("N"); void Awake() => _pickup = GetComponent<PowerPickup>(); void OnEnable() { _pickup.Collected += OnCollected; CollectibleLedger.Instance?.Register(LevelId, id); } // Presentation in Start, not OnEnable: deactivating a GameObject while it is // still being activated logs an error. void Start() { var ledger = CollectibleLedger.Instance; if (ledger == null || !ledger.IsFound(LevelId, id)) return; if (hideIfFound) gameObject.SetActive(false); else if (ghostVisual != null) ghostVisual.SetActive(true); } void OnDisable() => _pickup.Collected -= OnCollected; void OnCollected(PowerPickup p, PickupCollector c) { CollectibleLedger.Instance?.MarkFound(LevelId, id); } #if UNITY_EDITOR public void EditorRegenerateId() { UnityEditor.Undo.RecordObject(this, "Regenerate Collectible ID"); id = System.Guid.NewGuid().ToString("N"); UnityEditor.EditorUtility.SetDirty(this); } #endif } } ``` **Why a GUID in `Reset`.** `Reset` runs when the component is first added (and on the Inspector's Reset command), so every new collectible gets a unique ID with zero effort. **The trap:** duplicating a GameObject (Ctrl+D) or placing a prefab instance copies the ID. That is why the validator below exists. Do not "fix" this with `OnValidate` that regenerates IDs, because `OnValidate` also runs on load and you would change IDs of objects already in players' saves. **Ghost visuals** follow a common convention: an already-found souvenir appears translucent, so the player knows they have it but the room does not look empty. The pickup's effects still run (coins, if any), but the ledger ignores the duplicate. ## 4.5 `CollectibleIdValidator.cs` (Editor) Put in an `Editor` folder. ```csharp #if UNITY_EDITOR using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; namespace PowerUps.EditorTools { public static class CollectibleIdValidator { [MenuItem("Tools/Power-Ups/Validate Collectible IDs")] static void Validate() => Run(fix: false); [MenuItem("Tools/Power-Ups/Fix Duplicate Collectible IDs")] static void Fix() => Run(fix: true); static void Run(bool fix) { // 6000.5: the overloads with FindObjectsSortMode are deprecated; this one includes inactive objects. var all = Object.FindObjectsByType<Collectible>(FindObjectsInactive.Include); var groups = all.GroupBy(c => c.LevelId + "/" + c.Id).Where(g => string.IsNullOrEmpty(g.First().Id) || g.Count() > 1).ToList(); if (groups.Count == 0) { Debug.Log(quot;[Collectibles] {all.Length} collectibles, all IDs unique."); return; } int fixedCount = 0; foreach (var g in groups) { var list = g.ToList(); Debug.LogWarning(quot;[Collectibles] Duplicate or empty ID '{g.Key}' on: {string.Join(", ", list.Select(c => c.name))}", list[0]); if (!fix) continue; // Keep the first one's ID (it may already be in saves); regenerate the rest. int start = string.IsNullOrEmpty(list[0].Id) ? 0 : 1; for (int i = start; i < list.Count; i++) { list[i].EditorRegenerateId(); fixedCount++; } } if (fix) Debug.Log(quot;[Collectibles] Regenerated {fixedCount} IDs. Save the scene(s)."); } } } #endif ``` `FindObjectsByType<T>(FindObjectsInactive)` is the 6000.5 replacement for the deprecated overloads that took `FindObjectsSortMode` (the 6000.5 Scripting Reference marks those obsolete). It only sees **loaded** scenes, so open each level (or all of them additively) before validating. A Unity Test Framework edit-mode test that opens every scene in Build Settings and runs the same check is a good CI addition ([[Unity Test Framework]], [[Build Automation and CI]]). ## 4.6 Check - Collect a gem, stop Play mode, play again: the gem is a ghost; the HUD says 1 / N. - Duplicate a gem in the scene, run **Validate**: one warning. Run **Fix**: the copy gets a new ID; the original keeps its ID. - Kill the process (Task Manager) right after collecting: on restart, progress is either the old or the new state, never a half-written file. ## 4.7 Exercises 1. Show "3 / 10 gems" on a world-space sign at the level exit, using `CollectibleFound`. 2. Write an Editor script that opens every level scene, counts `Collectible`s, and writes totals into a `LevelCatalog` ScriptableObject for the level-select screen. 3. Send `CollectibleFound` to [[Playtest Telemetry and Heatmaps]] and draw found vs missed souvenirs on the heatmap. ## Sources - `JsonUtility` (6000.5, no Dictionary support): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/JsonUtility.html - `Application.persistentDataPath` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Application-persistentDataPath.html - `Object.FindObjectsByType` (6000.5, sort-mode overloads deprecated): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Object.FindObjectsByType.html - `MonoBehaviour.Reset` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/MonoBehaviour.Reset.html - `System.IO.File.Replace`: https://learn.microsoft.com/dotnet/api/system.io.file.replace