對(duì)象池的實(shí)現(xiàn):
一、先定義個(gè)List集合用來(lái)存儲(chǔ)對(duì)象证杭,起初先在池子里放置一定數(shù)量的對(duì)象沪袭,并且把他設(shè)置為false湾宙;然后寫一個(gè)方法查找沒有激活的對(duì)象,并且返回一個(gè)激活的對(duì)象冈绊;如果池子中對(duì)象數(shù)量不夠侠鳄,重新再向池子里添加對(duì)象。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 腳本掛在到空物體上
/// </summary>
public class ObjectPool : MonoBehaviour {
public static ObjectPool current;
void Awake()
{
current = this;
}
//將被放入對(duì)象池中的預(yù)制體
GameObject objectPrb;
//池子大小
public int poolCapacity = 20;
//定義對(duì)象集合
public List<GameObject> pool;
//池子容量不夠時(shí)死宣,是否自動(dòng)擴(kuò)展池子
public bool willgrow = true;
void Start(){
//加載預(yù)設(shè)體
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++) //遍歷對(duì)象池伟恶,將未激活的對(duì)象傳遞出去
{
if ( ! pool[i].activeInHierarchy )
return pool[i];
}
if ( willgrow ) //當(dāng)池子中所有對(duì)象都激活了,但是還想激活顯示對(duì)象時(shí)毅该,擴(kuò)展池子
{
GameObject obj = Instantiate(objectPrb);
pool.Add(obj);
obj.SetActive(false);
return obj;
}
return null;
}
}
二博秫、創(chuàng)建控制腳本,調(diào)用對(duì)象池的函數(shù)
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);
}
}
三眶掌、預(yù)設(shè)體消失的時(shí)候只需要取消激活
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);
}
}