Files
riversong-code-showcase/Source/Riversong/Game/CommonServices/Pooling/PoolingServiceExtensions.cs
2026-05-21 16:04:49 +02:00

88 lines
2.8 KiB
C#

using UnityEngine;
using UnityEngine.Pool;
using Object = UnityEngine.Object;
namespace DanieleMarotta.RiversongCodeShowcase
{
public static class PoolingServiceExtensions
{
public static IObjectPool<GameObject> GetOrCreatePool(this IPoolingService poolingService, GameObject prefab, Transform folder = null)
{
var poolKey = prefab.GetInstanceID();
var pool = poolingService.GetPool<GameObject>(poolKey);
if (pool != null) return pool;
pool = new ObjectPool<GameObject>(
() =>
{
var go = Object.Instantiate(prefab, folder);
OnCreate(go, poolKey);
return go;
},
OnGet,
go => OnRelease(go, folder));
poolingService.AddPool(poolKey, pool);
return pool;
}
public static IObjectPool<T> GetOrCreatePool<T>(this IPoolingService poolingService, T prefab, Transform folder = null) where T : Component
{
var poolKey = prefab.GetInstanceID();
var pool = poolingService.GetPool<T>(poolKey);
if (pool != null) return pool;
pool = new ObjectPool<T>(
() =>
{
var component = Object.Instantiate(prefab, folder);
OnCreate(component.gameObject, poolKey);
return component;
},
component => OnGet(component.gameObject),
component => OnRelease(component.gameObject, folder));
poolingService.AddPool(poolKey, pool);
return pool;
}
private static void OnCreate(GameObject go, int poolKey)
{
go.AddComponent<PooledObject>().PoolKey = poolKey;
go.SetActive(false);
}
private static void OnGet(GameObject go)
{
go.transform.SetParent(null);
go.SetActive(true);
}
private static void OnRelease(GameObject go, Transform folder)
{
go.SetActive(false);
go.transform.SetParent(folder);
}
public static T Get<T>(this IPoolingService poolingService, int poolKey) where T : class
{
return poolingService.GetPool<T>(poolKey).Get();
}
public static void Release(this IPoolingService poolingService, GameObject go)
{
var poolKey = go.GetComponent<PooledObject>().PoolKey;
poolingService.GetPool<GameObject>(poolKey).Release(go);
}
public static void Release<T>(this IPoolingService poolingService, T component) where T : Component
{
var poolKey = component.GetComponent<PooledObject>().PoolKey;
poolingService.GetPool<T>(poolKey).Release(component);
}
}
}