Skip to content

Instantly share code, notes, and snippets.

@brenocogu
Last active February 15, 2023 01:31
Show Gist options
  • Save brenocogu/d4c8ecc72b72c3779a312986e5827eed to your computer and use it in GitHub Desktop.
Save brenocogu/d4c8ecc72b72c3779a312986e5827eed to your computer and use it in GitHub Desktop.
Pool hub is a simple way to create pools in runtime as you need them. Very useful to avoid Instantiate() and Destroy()
//Useful for generic pooling, autoincrement, creating pools. Everything Useful to pool
//I've made that for gameObjects but change it as you wish.
//Fell free to use it, you are awesome
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using System;
public struct PoolHub
{
public List<GameObject> hub;
bool useAutoIncrement;
Func<GameObject, bool> defaultQuery;
public PoolHub(GameObject prefabToUse, bool useAutoIncrement = true, int listInitialSize = 10)
{
hub = new List<GameObject>();
this.useAutoIncrement = useAutoIncrement;
defaultQuery = (gameObject) => !gameObject.activeSelf;
for (int i = 0; i <= listInitialSize; i++)
{
GameObject @object = UnityEngine.Object.Instantiate(prefabToUse);
@object.SetActive(false);
hub.Add(@object);
}
}
public GameObject GetFromPool(Func<GameObject, bool> querySelector = null)
{
if(querySelector == null)
querySelector = defaultQuery;
GameObject returnO = (hub.Where(querySelector).Any()) ? hub.Where(querySelector).First() : null;
//This is the Auto Increment.
if (returnO == null)
{
returnO = UnityEngine.Object.Instantiate(hub.First());
returnO.SetActive(false);
hub.Add(returnO);
}
return returnO;
}
public T GetFromPool<T>(Func<GameObject, bool> querySelector = null) where T: Component
{
GameObject oj = GetFromPool(querySelector);
T cachedComponent;
if (oj.TryGetComponent<T>(out cachedComponent))
return cachedComponent;
else
return null;
}
}
@brenocogu
Copy link
Author

[14/02/2023] Removing singleton pattern from this class. Now it is a struct for a better way of controlling pools in run-time
Better Linq and creation options. Better access methods and removed non mono pooling support

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment