介紹演示
在游戲中雄卷,大量使用的對象,重復(fù)的創(chuàng)建和銷毀妒潭,很耗費性能鳄炉,這個時候就要使用對象池技術(shù)拂盯,當(dāng)物體使用時谈竿,如果對象池中有团驱,從對象池中取出使用嚎花,沒有就創(chuàng)建紊选,不使用時候道逗,將物體放回對象池,隱藏
代碼演示
對象池腳本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPoolManager : MonoBehaviour
{
public static ObjectPoolManager Instance;
//對象池集合
public List<GameObject> ObjectPoolList = new List<GameObject>();
//對象預(yù)制體
public GameObject Object1;
//最大存放在對象池里面的個數(shù)
public int MaxCount = 100;
//將對象保存到對象池
public void Push(GameObject obj)
{
if (ObjectPoolList.Count < MaxCount)
{
ObjectPoolList.Add(obj);
}
else
{
Destroy(obj);
}
}
//從對象池中取出一個對象
public GameObject Pop()
{
if (ObjectPoolList.Count > 0)
{
GameObject go = ObjectPoolList[0];
ObjectPoolList.RemoveAt(0);
return go;
}
return Instantiate(Object1);
}
//清除對象池
public void Clear()
{
ObjectPoolList.Clear();
}
void Start()
{
ObjectPoolManager.Instance = this;
}
void Update()
{
}
}
控制腳本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectController : MonoBehaviour
{
//管理存在的對象(不在對象池中的對象);
public List<GameObject> AlreadyExit = new List<GameObject>();
public int RandomPos = 100;
void Start()
{
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//創(chuàng)建,從對象池中取出
GameObject bullet = ObjectPoolManager.Instance.Pop();
AlreadyExit.Add(bullet);
bullet.SetActive(true);
int RandomX = Random.Range(0, RandomPos);
int RandomY = Random.Range(0, RandomPos);
int RandomZ = Random.Range(0, RandomPos);
bullet.transform.localPosition = new Vector3(RandomX,RandomY,RandomZ);
}
if (Input.GetMouseButtonDown(1))
{
//刪除此蜈,放入對象池
ObjectPoolManager.Instance.Push(AlreadyExit[0]);
AlreadyExit[0].SetActive(false);
AlreadyExit.RemoveAt(0);
}
}
}