Skip to content

Instantly share code, notes, and snippets.

@maxattack
Last active August 29, 2015 13:57
Show Gist options
  • Save maxattack/9770806 to your computer and use it in GitHub Desktop.
Save maxattack/9770806 to your computer and use it in GitHub Desktop.
Object Pooling Example for Unity
using UnityEngine;
using System.Collections;
using Dbg = System.Diagnostics.Debug;
public class PoolingExample : MonoBehaviour {
PoolingExample next;
PoolingExample prefab;
bool IsPrefab { get { return prefab == null; } }
// call this method on prefabs to duplicate a new instance. Will fail
// to assert if called on instances.
public PoolingExample Alloc(Vector3 position, Quaternion rotation) {
Dbg.Assert(IsPrefab);
if (next) {
var result = next;
next = next.next;
result.transform.position = position;
result.transform.rotation = rotation;
result.next = null;
result.gameObject.SetActive(true);
return result;
} else {
var result = Instantiate(this, position, rotation) as PoolingExample;
result.prefab = this;
return result;
}
}
// Destroy() unused instances
void Drain() {
Dbg.Assert(IsPrefab);
while(next) {
var p = next;
next = next.next;
Destroy(p);
}
next = null;
}
// Call this method on instances to return them to the candidate pool
void Release() {
Dbg.Assert(!IsPrefab);
next = prefab.next;
prefab.next = this;
gameObject.SetActive(false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment