UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"create cube pooler"
using System.Collections.Generic; using UnityEngine; public class CubePooler : MonoBehaviour { public static CubePooler Instance; [SerializeField] private GameObject cubePrefab; [SerializeField] private int poolSize = 10; private List<GameObject> cubePool; private void Awake() { if (Instance == null) { Instance = this; } else { Destroy(gameObject); return; } InitializePool(); } private void InitializePool() { cubePool = new List<GameObject>(); for (int i = 0; i < poolSize; i++) { GameObject cube = Instantiate(cubePrefab); cube.SetActive(false); cubePool.Add(cube); } } public GameObject GetCube() { foreach (GameObject cube in cubePool) { if (!cube.activeInHierarchy) { cube.SetActive(true); return cube; } } // If no available cube, create a new one and add it to the pool GameObject newCube = Instantiate(cubePrefab); cubePool.Add(newCube); return newCube; } public void ReturnCube(GameObject cube) { cube.SetActive(false); } }