Created
December 2, 2019 09:44
-
-
Save BeautyfullCastle/962c2e5ab3e55d1cfa80bc2590cf1c7d to your computer and use it in GitHub Desktop.
Generic ObjectPool class can use in 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 System.Collections.Generic; | |
public class ObjectPool<T> where T : UnityEngine.Object | |
{ | |
private Queue<T> queue = null; | |
private T original = null; | |
private int capacity = 0; | |
public ObjectPool(T original, int capacity = 10) | |
{ | |
this.capacity = capacity; | |
queue = new Queue<T>(capacity); | |
this.original = original; | |
Enqueue(original, capacity); | |
} | |
public T Dequeue() | |
{ | |
if (queue.Count <= 0) | |
{ | |
Enqueue(original, capacity); | |
} | |
T obj = queue.Dequeue(); | |
TrySetActive(obj, true); | |
return obj; | |
} | |
public bool Return(T obj) | |
{ | |
if (obj == null) | |
{ | |
return false; | |
} | |
Enqueue(obj); | |
return true; | |
} | |
private void Enqueue(T original, int capacity) | |
{ | |
for (int i = 0; i < capacity; i++) | |
{ | |
T obj = UnityEngine.Object.Instantiate<T>(original); | |
Enqueue(obj); | |
} | |
} | |
private void Enqueue(T obj) | |
{ | |
queue.Enqueue(obj); | |
TrySetActive(obj, false); | |
} | |
private static void TrySetActive(T obj, bool value) | |
{ | |
if (obj is UnityEngine.GameObject) | |
{ | |
var gameObject = obj as UnityEngine.GameObject; | |
gameObject.SetActive(value); | |
} | |
else if (obj is UnityEngine.Component) | |
{ | |
var component = obj as UnityEngine.Component; | |
component.gameObject.SetActive(value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment