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