Advertisement
UnityCoder_Jay

ObjectPool.cs

Jan 8th, 2023 (edited)
719
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.28 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class ObjectPool : MonoBehaviour
  6. {
  7.     public static ObjectPool instance;
  8.     private List<GameObject> poolObject = new List<GameObject>();
  9.     public int AmountPooled = 10;
  10.     [SerializeField] private GameObject Objprefab; // Whatever object you want to pool.
  11.  
  12.     /// <summary>
  13.     /// Awake is called when the script instance is being loaded.
  14.     /// </summary>
  15.     private void Awake()
  16.     {
  17.         if (instance == null) {
  18.             instance=this;
  19.         }
  20.     }
  21.  
  22.     /// <summary>
  23.     /// Start is called on the frame when a script is enabled just before
  24.     /// any of the Update methods is called the first time.
  25.     /// </summary>
  26.     private void Start()
  27.     {
  28.         for (int i = 0; i < AmountPooled; i++)
  29.         {
  30.             GameObject obj = Instantiate(Objprefab);
  31.             obj.SetActive(false);
  32.             poolObject.Add(obj);
  33.         }
  34.     }
  35.  
  36.     public GameObject GetPooledOjbect() {
  37.         for (int i = 0; i < poolObject.Count; i++)
  38.         {
  39.             if (!poolObject[i].activeInHierarchy) // if not active in hierarchy..
  40.             {
  41.                 return poolObject[i];
  42.  
  43.             }
  44.         }
  45.         return null; // else return null.
  46.     }
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement