Skip to content

Instantly share code, notes, and snippets.

@Toqozz
Created October 6, 2019 06:22
Show Gist options
  • Save Toqozz/add6ff699b92f0533de25b9bbb2f3844 to your computer and use it in GitHub Desktop.
Save Toqozz/add6ff699b92f0533de25b9bbb2f3844 to your computer and use it in GitHub Desktop.
Unity Generic Object Pool. Allows `Pool.Get</SomeMonoBehaviour/>`. Useful for avoiding `GetComponent` in a pool.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pool : MonoBehaviour {
public List<PooledObject> objectsToPool;
private Dictionary<Type, Queue<PooledObject>> dict;
private void Awake() {
dict = new Dictionary<Type, Queue<PooledObject>>();
foreach (PooledObject obj in objectsToPool) {
Queue<PooledObject> queue = new Queue<PooledObject>();
for (int i = 0; i < 20; i++) {
var clone = Instantiate(obj, transform);
clone.Finished += ReQueue;
clone.gameObject.SetActive(false);
queue.Enqueue(clone);
}
dict.Add(obj.TypeOf(), queue);
}
}
public T Get<T>() where T : class {
var queue = dict[typeof(T)];
return queue.Dequeue().behaviourToPool as T;
}
public PooledObject GetPooledObject<T>() {
var queue = dict[typeof(T)];
return queue.Dequeue();
}
public Queue<PooledObject> GetQueue<T>() {
return dict[typeof(T)];
}
private void ReQueue(PooledObject obj) {
obj.gameObject.SetActive(false);
var queue = dict[obj.TypeOf()];
queue.Enqueue(obj);
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PooledObject : MonoBehaviour {
public MonoBehaviour behaviourToPool;
public Action<PooledObject> Finished;
public Type TypeOf() {
return behaviourToPool.GetType();
}
public void Finish() {
if (Finished != null) {
Finished(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment