Skip to content

Instantly share code, notes, and snippets.

@LiamDobbelaere
Created July 20, 2019 21:39
Show Gist options
  • Save LiamDobbelaere/b3ba6a933475d3d3bbfef57f09d1ca76 to your computer and use it in GitHub Desktop.
Save LiamDobbelaere/b3ba6a933475d3d3bbfef57f09d1ca76 to your computer and use it in GitHub Desktop.
Unity Object Pool
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
[System.Serializable]
public struct PoolConfiguration
{
public string objectName;
public PoolConfigurationSettings settings;
}
[System.Serializable]
public struct PoolConfigurationSettings
{
public GameObject objectTemplate;
public int initialPoolSize;
public int poolSizeIncrement;
}
//Used to allow the developer to configure the different pools in the inspector
public PoolConfiguration[] poolConfigurations;
//Dictionary to link an object name to a 'template' and other pool config settings
private Dictionary<string, PoolConfigurationSettings> poolDict;
//Dictionary to keep track of our instances so we can easily go through all instances
//of a certain type, bypassing the transform hierarchy (useful if there are multiple pools)
private Dictionary<string, List<GameObject>> instancesDict;
void Start()
{
poolDict = new Dictionary<string, PoolConfigurationSettings>();
instancesDict = new Dictionary<string, List<GameObject>>();
foreach (PoolConfiguration config in poolConfigurations)
{
poolDict.Add(config.objectName, config.settings);
instancesDict.Add(config.objectName, new List<GameObject>());
//Initialize this pool
Expand(config.objectName, config.settings.initialPoolSize);
}
}
GameObject[] Expand(string objectName, int amount)
{
GameObject template = poolDict[objectName].objectTemplate;
GameObject[] freshInstances = new GameObject[amount];
for (int i = 0; i < amount; i++)
{
var inst = Instantiate(template, transform, true);
inst.SetActive(false);
freshInstances[i] = inst;
instancesDict[objectName].Add(inst);
}
return freshInstances;
}
public GameObject Get(string objectName)
{
//Find the first available object
foreach (GameObject go in instancesDict[objectName])
{
if (!go.activeInHierarchy)
{
return go;
}
}
//If we get this far, we didn't find it,
//which means we should expand the pool and try again
GameObject freshInstance = Expand(objectName, poolDict[objectName].poolSizeIncrement)[0];
return freshInstance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment