A game about forced loneliness, made by TACStudios
1using System; 2using System.Collections.Generic; 3 4namespace Unity.VisualScripting 5{ 6 public static class GenericPool<T> where T : class, IPoolable 7 { 8 private static readonly object @lock = new object(); 9 private static readonly Stack<T> free = new Stack<T>(); 10 private static readonly HashSet<T> busy = new HashSet<T>(ReferenceEqualityComparer<T>.Instance); 11 12 public static T New(Func<T> constructor) 13 { 14 lock (@lock) 15 { 16 if (free.Count == 0) 17 { 18 free.Push(constructor()); 19 } 20 21 var item = free.Pop(); 22 23 item.New(); 24 25 busy.Add(item); 26 27 return item; 28 } 29 } 30 31 public static void Free(T item) 32 { 33 lock (@lock) 34 { 35 if (!busy.Remove(item)) 36 { 37 throw new ArgumentException("The item to free is not in use by the pool.", nameof(item)); 38 } 39 40 item.Free(); 41 42 free.Push(item); 43 } 44 } 45 } 46}