Last active
August 29, 2015 13:57
-
-
Save maxattack/9770806 to your computer and use it in GitHub Desktop.
Object Pooling Example for Unity
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; | |
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