using System; using System.Collections.Generic; using asap.core.common; using UnityEngine; namespace asap.core.common { public interface IObjectPoolService { IObjectPool CreatePool(Type objType, int preloadNum = 0, int maxSize = 0); void DestroyPool(Type objType); // void DestroyPool(IObjectPool pool); IObjectPool GetPool(Type type); // IObjectPool GetPool(); object SpawnObject(Type type); void DespawnObject(object obj); GameObjectPool CreatePool(T prefab, int preloadNum = 0, int maxSize = 0) where T : Component; } public static class ObjectPoolServiceExtensions { public static IObjectPool CreatePool(this IObjectPoolService service, int preloadNum = 0, int maxSize = 0) { return service.CreatePool(typeof(T), preloadNum, maxSize); } public static void DestroyPool(this IObjectPoolService service) { service.DestroyPool(typeof(T)); } public static IObjectPool GetPool(this IObjectPoolService service) { var type = typeof(T); return service.GetPool(type); } public static T SpawnObject(this IObjectPoolService service) { return (T)service.SpawnObject(typeof(T)); } } public class ObjectPoolService : IObjectPoolService { private Dictionary objectPoolDict; public ObjectPoolService() { objectPoolDict = new Dictionary(); } public void Update() { } public void OnDestroy() { foreach (var pool in objectPoolDict.Values) { pool.Release(); } objectPoolDict.Clear(); objectPoolDict = null; } public IObjectPool CreatePool(Type objType, int preloadNum = 0, int maxSize = 0) { if (objectPoolDict.TryGetValue(objType, out var pool)) return pool; pool = new ObjectPool(objType, preloadNum, maxSize); pool.Initialize(); objectPoolDict.Add(objType, pool); return pool; } public void DestroyPool(Type type) { if (!objectPoolDict.TryGetValue(type, out var pool)) return; pool.Release(); objectPoolDict.Remove(type); } public IObjectPool GetPool(Type type) { if(!objectPoolDict.TryGetValue(type, out var pool)) pool = CreatePool(type); return pool; } public object SpawnObject(Type type) { var pool = GetPool(type); if (pool == null) { pool = CreatePool(type); // return null; } return pool.SpawnObject(); } public void DespawnObject(object obj) { var pool = GetPool(obj.GetType()); if (pool == null) return; pool.DespawnObject(obj); } public GameObjectPool CreatePool(T prefab, int preloadNum = 0, int maxSize = 0) where T : Component { var type = typeof(T); if (!objectPoolDict.TryGetValue(type, out var pool)) { pool = new GameObjectPool(prefab, preloadNum, maxSize); pool.Initialize(); objectPoolDict.Add(type, pool); } return pool as GameObjectPool; } } }