Advertisement
johnnygoodguy2000

ObjectPooler.cs

Apr 7th, 2024 (edited)
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.11 KB | Gaming | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class ObjectPooler : MonoBehaviour
  6. {
  7.     public GameObject pooledObject;
  8.     public int pooledAmount;
  9.     List<GameObject> pooledObjects;
  10.    
  11.     // Start is called before the first frame update
  12.     void Start()
  13.     {
  14.         pooledObjects = new List<GameObject>();
  15.         for (int i = 0; i < pooledAmount; i++)
  16.         {
  17.             GameObject obj = Instantiate(pooledObject);
  18.             obj.SetActive(false);
  19.             pooledObjects.Add(obj);
  20.         }
  21.     }
  22.  
  23.     public GameObject GetPooledObject()
  24.     {
  25.         // Loop through the pooled objects and return the first inactive one
  26.         for (int i = 0; i < pooledObjects.Count; i++)
  27.         {
  28.             if (!pooledObjects[i].activeInHierarchy)
  29.             {
  30.                 return pooledObjects[i];
  31.             }
  32.         }
  33.  
  34.         // If no inactive object is found, instantiate a new one
  35.         GameObject newObj = Instantiate(pooledObject);
  36.         newObj.SetActive(false);
  37.         pooledObjects.Add(newObj);
  38.         return newObj;
  39.     }
  40. }
  41.  
  42.  
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement