對象池的實現:
一、先定義個List集合用來存儲對象,起初先在池子里放置一定數量的對象,并且把他設置為false;然后寫一個方法查找沒有激活的對象,并且返回一個激活的對象;如果池子中對象數量不夠,重新再向池子里添加對象。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 腳本掛在到空物體上
/// </summary>
public class ObjectPool : MonoBehaviour {
public static ObjectPool current;
void Awake()
{
current = this;
}
//將被放入對象池中的預制體
GameObject objectPrb;
//池子大小
public int poolCapacity = 20;
//定義對象集合
public List<GameObject> pool;
//池子容量不夠時,是否自動擴展池子
public bool willgrow = true;
void Start(){
//加載預設體
objectPrb= Resources.Load("Sphere")as GameObject;
for(int i = 0 ; i<poolCapacity ; i++)
{
GameObject obj = Instantiate(objectPrb);
pool.Add(obj);
obj.SetActive(false);
}
}
public GameObject GetPooledObject(){
for( int i = 0 ; i<pool.Count ; i++) //遍歷對象池,將未激活的對象傳遞出去
{
if ( ! pool[i].activeInHierarchy )
return pool[i];
}
if ( willgrow ) //當池子中所有對象都激活了,但是還想激活顯示對象時,擴展池子
{
GameObject obj = Instantiate(objectPrb);
pool.Add(obj);
obj.SetActive(false);
return obj;
}
return null;
}
}
二、創建控制腳本,調用對象池的函數
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 腳本掛在到空物體上
/// </summary>
public class Control : MonoBehaviour {
void Update () {
if (Input.GetMouseButtonDown(0))
{
Fire();
}
}
void Fire()
{
GameObject obj = ObjectPool.current.GetPooledObject();
if (obj == null)
{
return;
}
obj.transform.position = Vector3.one;
obj.transform.rotation = transform.rotation;
obj.SetActive(true);
}
}
三、預設體消失的時候只需要取消激活
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour {
void OnEnable()
{
Invoke("Destroy",2);
}
void Destroy() {
gameObject.SetActive(false);
}
void OnDisable(){
CancelInvoke();
}
void Update()
{
transform.Translate(transform.forward * 5f * Time.deltaTime);
}
}