Skip to content

Instantly share code, notes, and snippets.

@sanukin39
Created February 14, 2019 13:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sanukin39/d882b52046f8e80a0ff089badf597dce to your computer and use it in GitHub Desktop.
Save sanukin39/d882b52046f8e80a0ff089badf597dce to your computer and use it in GitHub Desktop.
Simple object pool for Unity
using UnityEngine;
using System.Collections.Generic;
public class ObjectPool
{
private const string ObjectPoolPrefix = "Pool";
private readonly GameObject _target;
private readonly Transform _poolParent;
private readonly List<GameObject> _objects;
public ObjectPool(GameObject poolingTarget)
{
_target = poolingTarget;
_objects = new List<GameObject>();
_poolParent = new GameObject().transform;
_poolParent.name = $"{ObjectPoolPrefix}{poolingTarget.name}";
}
public GameObject Get()
{
foreach (var go in _objects)
{
if (go.activeSelf)
{
continue;
}
go.SetActive(true);
return go;
}
var newObject = GameObject.Instantiate(_target, _poolParent);
_objects.Add(newObject);
return newObject;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment