unity3d对象池技术
游戏中经常会出现同一种对象的反复生成以及摧毁,消耗了大量系统资源,并且使得堆中出现了较多的难以利用的碎片,进一步降低了游戏流畅度。针对该问题,可以将已经“死亡”的对象收集起来,放置在对象池当中,当再次需要该类型的对象时,将该类对象从对象池中取出并且初始化。
综上所述,我们可以将对象池抽象为一个简单的链表,当链表为空时,则需要从内存中重新申请空闲区域,否则从链表中取出一个对象,并对其初始化操作。对于每个不同类型的对象,我们可以利用字典,为每个不同类型的对象按照的名称进行分类。
当一个对象“死亡”时,将其放入对象池中。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class objectPool
{
private static objectPool instance;
private Dictionary<string, List<GameObject>> pools;
private Dictionary<string, GameObject> prefabs;
private objectPool()
{
pools = new Dictionary<string, List<GameObject>>();
prefabs = new Dictionary<string, GameObject>();
}
public static objectPool getInstance()
{
if (instance == null)
{
instance = new objectPool();
}
return instance;
}
public GameObject getObject(GameObject obj)
{
string name = obj.name;
GameObject res = null;
if (pools.ContainsKey(name) && pools[name].Count > 0)
{
res = pools[name][0];
pools[name].RemoveAt(0);
res.SetActive(true);
return res;
}
GameObject prefab = null;
if (prefabs.ContainsKey(name))
{
prefab = prefabs[name];
}
else
{
prefab = Resources.Load<GameObject>("Prefabs/" + name);
prefabs.Add(name, prefab);
}
//Debug.Log(prefab.name);
res = GameObject.Instantiate(prefab);
res.name = name;
return res;
}
public void recycleObject(GameObject obj)
{
obj.SetActive(false);
if (!pools.ContainsKey(obj.name))
{
pools.Add(obj.name, new List<GameObject>());
}
pools[obj.name].Add(obj);
}
}
子弹对象的消亡过程
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bullet : MonoBehaviour
{
// Start is called before the first frame update
private float life=5f;
void OnEnable()
{
life = 5f;
}
void Update()
{
life -= Time.deltaTime;
if (life < 0)
{
objectPool.getInstance().recycleObject(gameObject);
}
this.gameObject.transform.Translate(Time.deltaTime * Vector3.forward);
}
}