Design Pattern: Object Pool
C# Code
using UnityEngine;
using System.Collections.Generic;
public class ObjectPool : MonoBehaviour
{
public GameObject objectToPool;
public int amountToPool;
private List<GameObject> pooledObjects;
void Start()
{
pooledObjects = new List<GameObject>();
for (int i = 0; i < amountToPool; i++)
{
GameObject obj = Instantiate(objectToPool);
obj.SetActive(false);
pooledObjects.Add(obj);
}
}
public GameObject GetPooledObject()
{
for (int i = 0; i < pooledObjects.Count; i++)
{
if (!pooledObjects[i].activeInHierarchy)
{
return pooledObjects[i];
}
}
// If no inactive object is found, create a new one
GameObject obj = Instantiate(objectToPool);
pooledObjects.Add(obj);
return obj;
}
public void ReturnObjectToPool(GameObject obj)
{
obj.SetActive(false);
}
}Một hệ thống Object Pool đơn giản để tái sử dụng các đối tượng thay vì tạo và hủy liên tục, giúp tối ưu hiệu năng đáng kể, đặc biệt khi cần tạo nhiều đối tượng như đạn, kẻ địch.