Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class ObjectPooler : MonoBehaviour
- {
- public GameObject pooledObject;
- public int pooledAmount;
- List<GameObject> pooledObjects;
- // Start is called before the first frame update
- void Start()
- {
- pooledObjects = new List<GameObject>();
- for (int i = 0; i < pooledAmount; i++)
- {
- GameObject obj = Instantiate(pooledObject);
- obj.SetActive(false);
- pooledObjects.Add(obj);
- }
- }
- public GameObject GetPooledObject()
- {
- // Loop through the pooled objects and return the first inactive one
- for (int i = 0; i < pooledObjects.Count; i++)
- {
- if (!pooledObjects[i].activeInHierarchy)
- {
- return pooledObjects[i];
- }
- }
- // If no inactive object is found, instantiate a new one
- GameObject newObj = Instantiate(pooledObject);
- newObj.SetActive(false);
- pooledObjects.Add(newObj);
- return newObj;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement