Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- public class ObjectPool : MonoBehaviour
- {
- [SerializeField]
- private GameObject pooledObject;
- [SerializeField]
- private int poolSize;
- [SerializeField]
- private bool willGrow;
- private Transform poolContainer;
- public int TotalActiveObjects
- {
- get
- {
- int activeObjs = 0;
- for (int i = 0; i < pooledObjects.Count; i++)
- {
- if (pooledObjects[i].activeInHierarchy) { activeObjs++; }
- }
- return activeObjs;
- }
- }
- private List<GameObject> pooledObjects;
- void Awake()
- {
- poolContainer = new GameObject("Pool: " + pooledObject.name).transform;
- poolContainer.transform.parent = transform;
- pooledObjects = new List<GameObject>();
- for (int i = 0; i < poolSize; i++)
- {
- CreateAndAddNewObject();
- }
- }
- public GameObject GetPooledObject()
- {
- for (int i = 0; i < pooledObjects.Count; i++)
- {
- if(pooledObjects[i].activeInHierarchy == false)
- {
- return pooledObjects[i];
- }
- }
- if (willGrow)
- {
- Debug.Log("Added a New Item To Pool: " + transform.name);
- return CreateAndAddNewObject();
- }
- return null;
- }
- private GameObject CreateAndAddNewObject()
- {
- GameObject obj = (GameObject)Instantiate(pooledObject);
- obj.SetActive(false);
- obj.transform.parent = poolContainer.transform;
- obj.transform.localPosition = Vector3.zero;
- obj.transform.localRotation = Quaternion.identity;
- pooledObjects.Add(obj);
- return obj;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement