Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.