Last active
September 13, 2024 17:03
-
-
Save st4rdog/d6316bb8de1f02ce7408fa40f7b569d7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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