Skip to content

Instantly share code, notes, and snippets.

@rainbee2214
Created December 6, 2016 20:32
Show Gist options
  • Save rainbee2214/d35c22b2361d13c500045142caaa3845 to your computer and use it in GitHub Desktop.
Save rainbee2214/d35c22b2361d13c500045142caaa3845 to your computer and use it in GitHub Desktop.
Generic Object Pool
using UnityEngine;
using System.Collections.Generic;
using System.Collections;
using System;
public class ObjectPooler : MonoBehaviour
{
public static ObjectPooler pooler;
public bool autoGrow = true;
Dictionary<Type, List<GameObject>> pools;
Dictionary<Type, GameObject> parents;
public void Awake()
{
if (pooler == null)
{
pooler = this;
}
else if (pooler != this)
{
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}
pools = new Dictionary<Type, List<GameObject>>(); //Pools must be registered by some object in Start()
parents = new Dictionary<Type, GameObject>();
}
public void CreatePool(GameObject poolObject, Type type, int baseSize = 4)
{
parents[type] = new GameObject(type.ToString() + "s");
parents[type].transform.SetParent(transform);
pools[type] = new List<GameObject>();
for (int i = 0; i < baseSize; i++)
{
AddObject(type, poolObject, i);
}
}
void AddObject(Type type, GameObject poolObject, int i)
{
pools[type].Add(Instantiate<GameObject>(poolObject));
pools[type][i].transform.SetParent(parents[type].transform);
pools[type][i].name = type.ToString() + i;
pools[type][i].gameObject.SetActive(false);
}
public GameObject GetObject(Type type)
{
//return the first available (turned off), if none available -> autogrow? add new : return null;
foreach (GameObject g in pools[type])
{
if (!g.activeInHierarchy)
{
g.SetActive(true);
return g;
}
}
if (!autoGrow) return null;
AddObject(type, pools[type][0].gameObject, pools[type].Count);
return pools[type][pools[type].Count - 1];
}
}
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class TileGenerator : MonoBehaviour
{
//This tilePrefab is the object that is sent to the object pooler. It contains a MonoBehvaiour called BreakableTile.
GameObject tilePrefab;
Type type = typeof(BreakableTile);
void Awake()
{
tilePrefab = Resources.Load<GameObject>("TilePrefab"); //tilePrefab must be placed in the root of the Resources folder.
}
void Start()
{
ObjectPooler.pooler.CreatePool(tilePrefab, type);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment