Skip to content

Instantly share code, notes, and snippets.

@st4rdog
Last active September 13, 2024 17:03
Show Gist options
  • Save st4rdog/d6316bb8de1f02ce7408fa40f7b569d7 to your computer and use it in GitHub Desktop.
Save st4rdog/d6316bb8de1f02ce7408fa40f7b569d7 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
public class PoolList<T>
{
public List<(bool IsAvailable, T type)> Pool = new();
public (bool success, (bool IsAvailable, T instance) item) TryGetFromPool(out T value)
{
for (int i = 0; i < Pool.Count; i++)
{
if (Pool[i].IsAvailable)
{
var item = Pool[i];
item.IsAvailable = false;
Pool[i] = item;
value = item.type;
return (success: true, item);
}
}
value = default;
return (success: false, (false, default));
}
public void ReturnToPool(T instance)
{
for (int i = 0; i < Pool.Count; i++)
{
var item = Pool[i];
if (EqualityComparer<T>.Default.Equals(item.type, instance))
{
item.IsAvailable = true;
Pool[i] = item;
return;
}
}
}
/// <summary>
/// Populates pool using custom initFunction that returns the object you want added to the pool.
/// Example - Allows instantiating a prefab then returning it's CanvasGroup.
/// </summary>
public PoolList<T> Init(int size, Func<T> initFunction)
{
for (int i = 0; i < size; i++)
{
Pool.Add((IsAvailable: true, initFunction()));
}
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment