Created
February 14, 2019 13:29
-
-
Save sanukin39/d882b52046f8e80a0ff089badf597dce to your computer and use it in GitHub Desktop.
Simple object pool for Unity
This file contains hidden or 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.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