Advertisement
Guest User

ObjectPool

a guest
Aug 31st, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.49 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4.  
  5. public class ObjectPool : MonoBehaviour
  6. {
  7.     [SerializeField]
  8.     private GameObject pooledObject;
  9.     [SerializeField]
  10.     private int poolSize;
  11.     [SerializeField]
  12.     private bool willGrow;
  13.  
  14.     private Transform poolContainer;
  15.  
  16.     public int TotalActiveObjects
  17.     {
  18.         get
  19.         {
  20.             int activeObjs = 0;
  21.             for (int i = 0; i < pooledObjects.Count; i++)
  22.             {
  23.                 if (pooledObjects[i].activeInHierarchy) { activeObjs++; }
  24.             }
  25.             return activeObjs;
  26.         }
  27.     }
  28.  
  29.     private List<GameObject> pooledObjects;
  30.  
  31.     void Awake()
  32.     {
  33.         poolContainer = new GameObject("Pool: " + pooledObject.name).transform;
  34.         poolContainer.transform.parent = transform;
  35.  
  36.         pooledObjects = new List<GameObject>();
  37.         for (int i = 0; i < poolSize; i++)
  38.         {
  39.             CreateAndAddNewObject();
  40.         }
  41.     }
  42.  
  43.     public GameObject GetPooledObject()
  44.     {
  45.         for (int i = 0; i < pooledObjects.Count; i++)
  46.         {
  47.             if(pooledObjects[i].activeInHierarchy == false)
  48.             {
  49.                 return pooledObjects[i];
  50.             }
  51.         }
  52.  
  53.         if (willGrow)
  54.         {
  55.             Debug.Log("Added a New Item To Pool: " + transform.name);
  56.             return CreateAndAddNewObject();
  57.         }
  58.  
  59.         return null;
  60.     }
  61.  
  62.     private GameObject CreateAndAddNewObject()
  63.     {
  64.         GameObject obj = (GameObject)Instantiate(pooledObject);
  65.         obj.SetActive(false);
  66.         obj.transform.parent = poolContainer.transform;
  67.         obj.transform.localPosition = Vector3.zero;
  68.         obj.transform.localRotation = Quaternion.identity;
  69.         pooledObjects.Add(obj);
  70.         return obj;
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement