自我介紹
廣東雙非一本的大三小白,計科專業,想在製作畢設前夯實基礎,畢設做出一款屬於自己的遊戲!
對象池
- 當我們在unity場景中需要多次重複的對某一個GameObject進行創建和銷燬時,減少GC給遊戲帶來的卡頓。
- 當我們在unity中銷燬物體上,並不會真的在內存中去釋放空間,只是斷開引用,最終的釋放空間是在當內存滿的時候進行GC
- 當場景中不需要該GameObject時,不進行銷燬,只是將其隱藏,放在對象池中管理,需要時從對象池中拿出來顯示
- 在unity,往往不止需要一種GameObject的對象池,這時我們需要用到字典(Dictionary)來存放和區分對象池)
緩存池模塊
我們需要兩個池子:
- 小池子 PoolData.cs 爲了解決層級問題,一個pool管理一種東西
- 大池子 PoolManager.cs 相當於管理所有小池子
PoolData.cs
using System.Collections.Generic;
using UnityEngine;
public class PoolData
{
public GameObject fatherObj; // 對象掛載的父節點
public List<GameObject> poolList;
public PoolData(GameObject obj, GameObject poolObj)
{
fatherObj = new GameObject(obj.name);
fatherObj.transform.parent = poolObj.transform;
poolList = new List<GameObject>() { obj };
PushObj(obj);
}
public void PushObj(GameObject obj)
{
obj.SetActive(false);
poolList.Add(obj);
obj.transform.parent = fatherObj.transform;
}
public GameObject GetObj()
{
GameObject obj = null;
obj = poolList[0];
poolList.RemoveAt(0);
obj.SetActive(true);
obj.transform.parent = null;
return obj;
}
}
核心 PoolManager.cs 封裝
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolManager : BaseSingleton<PoolManager>
{
public Dictionary<string, PoolData> poolDic = new Dictionary<string, PoolData>();
private GameObject poolObj;
public GameObject GetObj(string name)
{
GameObject obj = null;
if (poolDic.ContainsKey(name) && poolDic[name].poolList.Count > 0)
{
obj = poolDic[name].GetObj();
}
else
{
obj = GameObject.Instantiate(Resources.Load<GameObject>(name));
obj.name = name;
}
return obj;
}
public void PushObj(string name, GameObject obj)
{
if (poolObj == null) poolObj = new GameObject("Pool");
if (poolDic.ContainsKey(name))
{
poolDic[name].PushObj(obj);
}
else
{
poolDic.Add(name, new PoolData(obj, poolObj));
}
}
// 清空緩存池的方法,主要用於場景切換
public void Clear()
{
poolDic.Clear();
poolObj = null;
}
}
測試 Test.cs 隨便掛載到一個物體上,主要用緩存池來生成對象
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GameObject go = PoolManager.Instance().GetObj("Cube");
StartCoroutine(Back(go));
}
if (Input.GetMouseButtonDown(1))
{
GameObject go = PoolManager.Instance().GetObj("Sphere");
StartCoroutine(Back(go));
}
}
IEnumerator Back(GameObject go)
{
yield return new WaitForSeconds(1f);
PoolManager.Instance().PushObj(go.name, go);
}
生成的對象是預製體,放在Resources裏,上面測試腳本的協程是用於1秒後放回緩存池
效果