对象池
在使用unity3d做游戏时,经常有同一个Prefab用到多次,需要反复实例化(Instantiate)。但实例化是很消耗资源的,所以在游戏加载时把一批Prefab实例化好放在对象池中,游戏中用的时候拿出来,不用的时候放回去,避免反复申请和销毁。
存入对象池的元素应具有如下特征:1>场景中大量使用 2>存在一定的生命周期,会较为频繁的申请和释放。
作用;减少内存,优化游戏流畅程度。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//对象池管理器
public class PoolTest : MonoBehaviour {
//集合
public List list = new List();
//游戏预设体
public GameObject GoPrefab;
//最大个数
public int MaxCount = 100;
// Use this for initialization
//对象保存到对象中
public void push(GameObject go)
{
if (list.Count < MaxCount)
{
list.Add(go);
}
else {
Destroy(go);
}
}
//从对象池中取出一个对象
public GameObject Pop() {
if (list.Count > 0)
{
if (list.Count > 0)
{
GameObject go = list[0];
list.RemoveAt(0);
return go;
}
}
return Instantiate(GoPrefab);
}
//清楚对象池
public void clera() {
list.Clear();
}
}
1.创建一个cube,设为预设体
2.创建一个空物体,挂载PoolTest 脚本,和test脚本。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
private List list = new List();
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//创建
//从对象池取出
GameObject go = GetComponent<PoolTest>().Pop();
go.SetActive(true);
}
if (Input.GetMouseButtonUp(1))
{
//删除
//放入对象池
if (list.Count > 0)
{
GetComponent<PoolTest>().push(list[0]);
list[0].SetActive(false);
list.RemoveAt(0);
}
}
}
}