泛型对象池
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool<T> where T : MonoBehaviour
{
private T prefab;
private List<T> pool;
public ObjectPool(T prefab, int initialSize)
{
this.prefab = prefab;
pool = new List<T>();
for (int i = 0; i < initialSize; i++)
{
T obj = Object.Instantiate(prefab);
obj.gameObject.SetActive(false);
pool.Add(obj);
}
}
public T GetObject()
{
foreach (T obj in pool)
{
if (!obj.gameObject.activeSelf)
{
obj.gameObject.SetActive(true);
return obj;
}
}
T newObj = Object.Instantiate(prefab);
pool.Add(newObj);
return newObj;
}
public void ReturnObject(T obj)
{
obj.gameObject.SetActive(false);
}
}
调用
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float speed = 5f;
private void Update()
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
private void OnBecameInvisible()
{
BulletManager.Instance.ReturnBulletToPool(this.gameObject);
}
}
using UnityEngine;
public class BulletManager : MonoBehaviour
{
public static BulletManager Instance;
public GameObject bulletPrefab;
public int initialPoolSize = 10;
private ObjectPool<Bullet> bulletPool;
private void Awake()
{
Instance = this;
}
private void Start()
{
bulletPool = new ObjectPool<Bullet>(bulletPrefab.GetComponent<Bullet>(), initialPoolSize);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Bullet bullet = bulletPool.GetObject();
bullet.transform.position = transform.position;
bullet.gameObject.SetActive(true);
}
}
public void ReturnBulletToPool(GameObject bullet)
{
bulletPool.ReturnObject(bullet.GetComponent<Bullet>());
}
}