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