Skip to content

Instantly share code, notes, and snippets.

@brenocogu
Last active April 23, 2025 14:54
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.
[Deprecated] 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

Deprecated notice: Unity now offers a solution for handling object pools:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Pool.ObjectPool_1.html

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