using System; using System.Collections.Generic; using UnityEngine; using UnityGameFramework.Runtime; namespace SepCore.Components { [DisallowMultipleComponent] public class ChildrenMap : MonoBehaviour { [Serializable] public class Entry { [SerializeField] private string _key = string.Empty; [SerializeField] private GameObject _target = null; public string Key => _key; public GameObject Target => _target; public Entry() { } public Entry(string key, GameObject target) { _key = key; _target = target; } } [SerializeField] private List _entries = new List(); private Dictionary _map; private void Awake() { InitMap(); } public GameObject Get(string key) { if (_map == null) { InitMap(); } if (string.IsNullOrEmpty(key)) { Log.Error("[ChildrenMap] Key is null or empty when getting child on '{0}'.", gameObject.name); return null; } if (!_map.TryGetValue(key, out GameObject target)) { Log.Error("[ChildrenMap] Key '{0}' not found on '{1}'.", key, gameObject.name); return null; } if (target == null) { Log.Error("[ChildrenMap] Target GameObject for key '{0}' is null on '{1}'.", key, gameObject.name); return null; } return target; } private void InitMap() { if (_map != null) { return; } _map = new Dictionary(_entries.Count); for (int i = 0; i < _entries.Count; i++) { Entry entry = _entries[i]; if (entry == null) { continue; } if (string.IsNullOrEmpty(entry.Key)) { Log.Error("[ChildrenMap] Key is null or empty on '{0}'.", gameObject.name); continue; } if (_map.ContainsKey(entry.Key)) { Log.Error("[ChildrenMap] Duplicate key '{0}' on '{1}'.", entry.Key, gameObject.name); continue; } _map.Add(entry.Key, entry.Target); } } #if UNITY_EDITOR private void OnValidate() { if (_entries == null) { return; } var seenKeys = new HashSet(); for (int i = 0; i < _entries.Count; i++) { Entry entry = _entries[i]; if (entry == null || string.IsNullOrEmpty(entry.Key)) { continue; } if (!seenKeys.Add(entry.Key)) { Debug.LogWarning($"[ChildrenMap] Duplicate key '{entry.Key}' detected on '{gameObject.name}'.", this); } } } #endif } }