Advertisement
Muk99

ObjectPool

Mar 17th, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.19 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using Object = UnityEngine.Object;
  6.  
  7. public class ObjectPool<T> where T : Component {
  8.  
  9.     public List<T> objects { get; private set; }
  10.     public T objReference { get; private set; }
  11.     public Transform parent { get; private set; }
  12.  
  13.     public ObjectPool(T obj) : this(obj, 0, null) { }
  14.  
  15.     public ObjectPool(T obj, int amount) : this(obj, amount, null) { }
  16.  
  17.     public ObjectPool(T obj, Transform parent) : this(obj, 0, parent) { }
  18.  
  19.     public ObjectPool(T obj, int amount, Transform parent) {
  20.         if(!obj)
  21.             throw new ArgumentException("Object can't be null");
  22.  
  23.         objects = new List<T>();
  24.         objReference = obj;
  25.         this.parent = parent;
  26.  
  27.         CreateNew(amount);
  28.     }
  29.  
  30.     public void SetFree(T obj) {
  31.         if(!objects.Contains(obj))
  32.             throw new ArgumentException("Object is not in objects list");
  33.  
  34.         obj.gameObject.SetActive(false);
  35.     }
  36.  
  37.     public T GetFree() {
  38.         var freeObject = (from item in objects
  39.                           where !item.gameObject.activeSelf
  40.                           select item).FirstOrDefault();
  41.  
  42.         if(!freeObject)
  43.             freeObject = CreateNew();
  44.  
  45.         freeObject.gameObject.SetActive(true);
  46.         return freeObject;
  47.     }
  48.  
  49.     public T GetFree(Vector3 position, Quaternion rotation) {
  50.         var freeObject = GetFree();
  51.  
  52.         freeObject.transform.position = position;
  53.         freeObject.transform.rotation = rotation;
  54.  
  55.         return freeObject;
  56.     }
  57.  
  58.     public T CreateNew() {
  59.         var newObject = Object.Instantiate(objReference);
  60.         newObject.name = newObject.name.Replace("(Clone)", "");
  61.         newObject.gameObject.SetActive(false);
  62.  
  63.         if(parent)
  64.             newObject.transform.SetParent(parent);
  65.  
  66.         objects.Add(newObject);
  67.         return newObject;
  68.     }
  69.  
  70.     public T[] CreateNew(int amount) {
  71.         var objs = new T[amount];
  72.  
  73.         for(int i = 0; i < amount; i++)
  74.             objs[i] = CreateNew();
  75.  
  76.         return objs;
  77.     }
  78.  
  79.     public static implicit operator bool(ObjectPool<T> exists) {
  80.         return exists != null;
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement