Create a gist now

Instantly share code, notes, and snippets.

A simple pooling system for Unity plus a helper for Shuriken particles to do one-shot particle effects in a pool. Put the pool component on an object and set the name and prefab. The pool invokes the OnPoolCreate method on objects when they are "created" in the pool (so put your logic that normally would go in Start there) and an OnPoolRelease m…
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GameObjectPool : MonoBehaviour
{
private static readonly Dictionary<string, GameObjectPool> _poolsByName = new Dictionary<string, GameObjectPool>();
public static GameObjectPool GetPool(string name) { return _poolsByName[name]; }
[SerializeField]
private string _poolName = string.Empty;
[SerializeField]
private Transform _prefab = null;
[SerializeField]
private int _initialCount = 10;
[SerializeField]
private bool _parentInstances = true;
private readonly Stack<Transform> _instances = new Stack<Transform>();
void Awake()
{
System.Diagnostics.Debug.Assert(_prefab);
_poolsByName[_poolName] = this;
for (int i = 0; i < _initialCount; i++)
{
var t = Instantiate(_prefab) as Transform;
InitializeInstance(t);
ReleaseInstance(t);
}
}
public Transform GetInstance(Vector3 position = new Vector3())
{
Transform t = null;
if (_instances.Count > 0)
{
t = _instances.Pop();
}
else
{
Debug.LogWarning(_poolName + " pool ran out of instances!", this);
t = Instantiate(_prefab) as Transform;
}
t.position = position;
InitializeInstance(t);
return t;
}
private void InitializeInstance(Transform instance)
{
if (_parentInstances)
{
instance.parent = transform;
}
instance.gameObject.SetActiveRecursively(true);
instance.BroadcastMessage("OnPoolCreate", this, SendMessageOptions.DontRequireReceiver);
}
public void ReleaseInstance(Transform instance)
{
instance.BroadcastMessage("OnPoolRelease", this, SendMessageOptions.DontRequireReceiver);
instance.gameObject.SetActiveRecursively(false);
_instances.Push(instance);
}
}
GameObjectPool pool = GameObjectPool.GetPool("Explosions");
Transform instance = pool.GetInstance(Vector3.zero);
// configure instance however you want, or don't. :)
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(ParticleSystem))]
public class PooledParticleSystem : MonoBehaviour
{
private GameObjectPool _pool;
void OnPoolCreate(GameObjectPool pool)
{
_pool = pool;
particleSystem.renderer.enabled = true;
particleSystem.time = 0;
particleSystem.Clear(true);
particleSystem.Play(true);
}
void OnPoolRelease()
{
particleSystem.Stop();
particleSystem.time = 0;
particleSystem.Clear(true);
particleSystem.renderer.enabled = false;
}
void Update()
{
if (!particleSystem.IsAlive(true) && particleSystem.renderer.enabled)
{
_pool.ReleaseInstance(transform);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment