我们通常在项目中,如果说引用了大量的同种预制体但是如子弹等有一定生命周期的,我们就可以使用对象池来做一些基本的简单优化。
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;
namespace D_Bug{
public class GameObjectPoolTwo : MonoBehaviour
{
#region Variables
public static GameObjectPoolTwo Instance;
private Transform _allPoolDataParent = null;
private void Awake()
{
Instance = this;
_allPoolDataParent = new GameObject("GameObjectPool").transform;
}
#endregion
private Dictionary<string, OnePoolData> _objectPool = new Dictionary<string, OnePoolData>();
public void ReleaseItem(GameObject item)
{
if (!_objectPool.ContainsKey(item.name))
{
CreateOneDataPool(_allPoolDataParent, item.name);
}
_objectPool[item.name].Pool.Release(item);
}
public GameObject GetItem(string itemName)
{
if (!_objectPool.ContainsKey(itemName))
{
CreateOneDataPool(_allPoolDataParent, itemName);
}
return _objectPool[itemName].Pool.Get();
}
public void CreateOneDataPool(Transform allPoolParent,string itenName)
{
_objectPool.Add(itenName, new OnePoolData(allPoolParent, itenName));
}
public void Clear()
{
_objectPool.Clear();
}
}
public class OnePoolData
{
public ObjectPool<GameObject> Pool;
private Transform _smallPoolParent;
private string _itemPath;
public OnePoolData(Transform allPoolParent,string itemName)
{
_smallPoolParent = new GameObject(itemName).transform;
_smallPoolParent.SetParent(allPoolParent);
_itemPath = itemName;
Pool = new ObjectPool<GameObject>(Create, Get, Release, null, true, 20, 100);
}
private GameObject Create()
{
GameObject item = GameObject.Instantiate(Resources.Load<GameObject>(_itemPath));
item.name = _itemPath;
return item;
}
private void Get(GameObject obj)
{
obj.SetActive(true);
}
private void Release(GameObject obj)
{
obj.SetActive(false);
obj.transform.SetParent(_smallPoolParent);
}
}
}