Last active
May 4, 2020 20:40
-
-
Save mukaschultze/5bc426e74ee3ee44923cea5202383ab7 to your computer and use it in GitHub Desktop.
Unity - Object Pool
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; | |
using System.Collections.Generic; | |
using System.Linq; | |
using UnityEngine; | |
using Object = UnityEngine.Object; | |
public class ObjectPool<T> where T : Component { | |
public List<T> objects { get; private set; } | |
public T objReference { get; private set; } | |
public Transform parent { get; private set; } | |
public ObjectPool(T obj) : this(obj, 0, null) { } | |
public ObjectPool(T obj, int amount) : this(obj, amount, null) { } | |
public ObjectPool(T obj, Transform parent) : this(obj, 0, parent) { } | |
public ObjectPool(T obj, int amount, Transform parent) { | |
if(!obj) | |
throw new ArgumentException("Object can't be null"); | |
objects = new List<T>(); | |
objReference = obj; | |
this.parent = parent; | |
CreateNew(amount); | |
} | |
public void SetFree(T obj) { | |
obj.gameObject.SetActive(false); | |
} | |
public T GetFree() { | |
var freeObject = objects.FirstOrDefault(obj => !obj.activeSelf); | |
if(!freeObject) | |
freeObject = CreateNew(); | |
freeObject.gameObject.SetActive(true); | |
return freeObject; | |
} | |
public T GetFree(Vector3 position, Quaternion rotation) { | |
var freeObject = GetFree(); | |
freeObject.transform.position = position; | |
freeObject.transform.rotation = rotation; | |
return freeObject; | |
} | |
public T CreateNew() { | |
var newObject = Object.Instantiate(objReference); | |
newObject.name = newObject.name.Replace("(Clone)", ""); | |
newObject.gameObject.SetActive(false); | |
if(parent) | |
newObject.transform.SetParent(parent); | |
objects.Add(newObject); | |
return newObject; | |
} | |
public T[] CreateNew(int amount) { | |
var objs = new T[amount]; | |
for(int i = 0; i < amount; i++) | |
objs[i] = CreateNew(); | |
return objs; | |
} | |
public static implicit operator bool(ObjectPool<T> exists) { | |
return exists != null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment