介绍演示
在游戏中,大量使用的对象,重复的创建和销毁,很耗费性能,这个时候就要使用对象池技术,当物体使用时,如果对象池中有,从对象池中取出使用,没有就创建,不使用时候,将物体放回对象池,隐藏
o1.png代码演示
对象池脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPoolManager : MonoBehaviour
{
public static ObjectPoolManager Instance;
//对象池集合
public List<GameObject> ObjectPoolList = new List<GameObject>();
//对象预制体
public GameObject Object1;
//最大存放在对象池里面的个数
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))
{
//创建,从对象池中取出
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);
}
}
}
网友评论