Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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) {
- if(!objects.Contains(obj))
- throw new ArgumentException("Object is not in objects list");
- obj.gameObject.SetActive(false);
- }
- public T GetFree() {
- var freeObject = (from item in objects
- where !item.gameObject.activeSelf
- select item).FirstOrDefault();
- 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;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement