Last active
December 30, 2015 18:29
-
-
Save maxattack/7867605 to your computer and use it in GitHub Desktop.
No-frills GameObject pooling in Unity. KISS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
// CustomBehaviour is just a trivial subclass of MonoBehaviour with a bunch | |
// of static finger-friendly helper-functions :P | |
public class PooledObject : CustomBehaviour { | |
// subclass this to treat a behaviour as the basis | |
// of a poolable object. Stores simple metadata | |
// related to pooling | |
internal GameObjectPool pool; | |
internal PooledObject next; | |
public void PutBack() { | |
// Return to the pool, if it's still around, otherwise | |
// just plain-old destroy this object. Either way it'll | |
// be out of the scene. | |
if (pool) { | |
pool.PutBack( this ); | |
} else { | |
Destroy( gameObject ); | |
} | |
} | |
} | |
public class GameObjectPool : CustomBehaviour { | |
// designer params (forces designers to subclass PooledObject) | |
public PooledObject prefab; | |
// head reference for a plain-old linked-list | |
PooledObject firstIdle; | |
public PooledObject TakeOut() { | |
if (firstIdle != null) { | |
// activate an old instance | |
var result = firstIdle; | |
firstIdle = firstIdle.next; | |
result.next = null; | |
result.gameObject.SetActive( true ); | |
return result; | |
} else { | |
// instantiate a new instance | |
var result = Dup( prefab ); | |
result.pool = this; | |
return result; | |
} | |
} | |
public void PutBack(PooledObject obj) { | |
Assert(obj.pool == this); | |
// prepend to the head of the linked list | |
obj.gameObject.SetActive( false ); | |
obj.next = firstIdle; | |
firstIdle = obj; | |
} | |
public void Drain() { | |
// destroy all the idle instances | |
while(firstIdle != null) { | |
var prev = firstIdle; | |
firstIdle = firstIdle.next; | |
Destroy( prev.gameObject ); | |
} | |
} | |
void OnDestroy() { | |
// take out the idle instances when you diiieee | |
Drain(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The only gotcha to watch out for is that OnEnable() will be invoked before Start(), but as long as you know that you should be gravy.