Neg_Utils/NativePool.cs
2025-10-06 17:31:41 +02:00

47 lines
926 B
C#

using System;
using System.Collections.Generic;
using UnityEngine.Assertions;
namespace NegUtils;
public interface NativePool<T> where T : class, IPoolable
{
private static readonly List<T> Instances = new(10);
public static T Get()
{
T item;
if (Instances.Count == 0)
item = Activator.CreateInstance<T>();
else
{
item = Instances[^1];
Instances.RemoveAt(Instances.Count - 1);
}
item.OnGet();
return item;
}
public static void Return(T obj)
{
Assert.IsNotNull(obj);
obj.OnRelease();
if(Instances.Count >= Capacity)
return;
Instances.Add(obj);
}
public static int Capacity
{
get => Instances.Count;
set => Instances.Capacity = value;
}
}
public interface IPoolable
{
void OnGet();
void OnRelease();
}