using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.AddressableAssets; namespace Jovian.EncounterSystem { /// /// Central lookup cache mapping to its owning /// across one or more assets. /// In editor the registry auto-populates via an asset postprocessor; at runtime call /// explicitly after load. /// [CreateAssetMenu(fileName = "EncounterRegistry", menuName = "Jovian/Encounter System/Encounter Registry")] public class EncounterRegistry : ScriptableObject { /// Collections whose encounters should be indexed. public EncountersCollection[] encounterCollections = Array.Empty(); private readonly Dictionary encounters = new(); /// The live id → encounter map. public Dictionary GetEncounters() => encounters; /// Add an encounter to the cache if its id isn't already present. public void RegisterEncounter(IEncounter encounter) { encounters?.TryAdd(encounter?.EncounterDefinition?.internalId, encounter); } /// Remove an encounter from the cache by its id. public void UnregisterEncounter(IEncounter encounter) { encounters.Remove(encounter.EncounterDefinition.internalId); } /// Clear the cache. Call before a full re-population to avoid stale entries. public void ClearEncounters() { encounters.Clear(); } /// Walk and register every encounter found. /// Call first if you need a clean state. public void PopulateEncounters() { foreach(var collection in encounterCollections) { foreach(var encounter in collection.encounterTables) { foreach(var encounterInstance in encounter.encounters) { RegisterEncounter(encounterInstance); } } } } } #if UNITY_EDITOR /// /// Editor-time hook that keeps an asset (located via Addressables /// key "EncounterRegistry") in sync with asset edits: clears and repopulates on any asset /// import/move/delete. /// public class EncounterRegister : UnityEditor.AssetPostprocessor { private static EncounterRegistry registryCache; private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { registryCache ??= Addressables.LoadAssetAsync("EncounterRegistry").WaitForCompletion(); registryCache.ClearEncounters(); registryCache.PopulateEncounters(); } } #endif }