using System.Collections.Generic; using GameFramework.ObjectPool; using GeometryTD.PoolObjectBase; using UnityEngine; using UnityGameFramework.Runtime; namespace GeometryTD.UI { public class CompArea : MonoBehaviour { [SerializeField] private Transform m_Content; [SerializeField] private RepoItem m_ItemTemplate; [SerializeField] private int m_InstancePoolCapacity = 64; private readonly List m_ActiveItems = new List(); private readonly Dictionary m_ItemMap = new Dictionary(); private IObjectPool m_ItemPool; private string m_PoolName; public void OnInit(CompAreaContext context) { if (context == null) { OnReset(); return; } EnsurePool(); OnReset(); if (context.Items == null || context.Items.Length == 0) { return; } for (int i = 0; i < context.Items.Length; i++) { RepoItem item = CreateOrSpawnItem(); if (item == null) { continue; } item.gameObject.SetActive(true); item.OnInit(context.Items[i]); m_ActiveItems.Add(item); m_ItemMap[context.Items[i].InstanceId] = item; } } public void OnReset() { for (int i = m_ActiveItems.Count - 1; i >= 0; i--) { RepoItem item = m_ActiveItems[i]; if (item == null) { continue; } item.OnReset(); item.gameObject.SetActive(false); m_ItemPool?.Unspawn(item); } m_ActiveItems.Clear(); m_ItemMap.Clear(); } private void OnDestroy() { OnReset(); m_ItemPool?.ReleaseAllUnused(); } private void EnsurePool() { if (m_ItemPool != null) { return; } m_PoolName = $"RepoItemPool_{GetInstanceID()}"; m_ItemPool = GameEntry.ObjectPool.CreateSingleSpawnObjectPool(m_PoolName, m_InstancePoolCapacity); } private RepoItem CreateOrSpawnItem() { if (m_ItemPool == null) { return null; } RepoItemObject itemObject = m_ItemPool.Spawn(); RepoItem item = itemObject != null ? (RepoItem)itemObject.Target : null; if (item == null) { if (m_ItemTemplate == null) { Log.Warning("CompArea requires an item template."); return null; } item = Instantiate(m_ItemTemplate); m_ItemPool.Register(RepoItemObject.Create(item), true); } if (m_Content != null) { item.transform.SetParent(m_Content, false); } return item; } public void SetItemSelected(long itemId, bool isSelected) { if (!m_ItemMap.TryGetValue(itemId, out RepoItem item)) { return; } item.SetSelected(isSelected); } } }