对象池的作用
避免一直重复的创建和销毁某个对象,增加消耗
理解
就是在开辟一个地方,去储存会大量实例化和销毁的对象(最典型的就是FPS游戏里面的子弹),对象池就是给这些实例化的对象有个地方住着,而不是因为无家可归就被鲨了,当下次再需要的时候就可以直接利用而不是需要再生一个(毕竟生孩子需要很大的消耗 哈哈哈哈o(*≧▽≦)ツ┏━┓)。
对象池最少需要两个功能
1.获取对象
2.回收对象
不说废话上代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjPool : MonoBehaviour
{
// Use this for initialization
public static ObjPool _instance;
private Dictionary<string, List<GameObject>> _pool = new Dictionary<string, List<GameObject>>();
private Dictionary<string, GameObject> _prefab = new Dictionary<string, GameObject>();
void Awake()
{
_instance = this;
}
// Update is called once per frame
void Update()
{
}
/// <summary>
/// 在对象池获取对象
/// </summary>
/// <param name="objName">对象名称</param>
/// <returns></returns>
public GameObject GetObj(string objName)
{
GameObject result = null;
if (_pool.ContainsKey(objName))
{
if (_pool[objName].Count > 0)
{
result = _pool[objName][0];
result.SetActive(true);
_pool[objName].Remove(result);
return result;
}
}
GameObject prefab = null;
if (_prefab.ContainsKey(objName))
{
prefab = _prefab[objName];
}
else
{
prefab = Resources.Load<GameObject>("Prefabs/" + objName);
_prefab.Add(objName, prefab);
}
result = Instantiate(prefab);
result.name = objName;
return result;
}
/// <summary>
/// 回收到对象池
/// </summary>
/// <param name="obj"></param>
public void RecycleObj(GameObject obj)
{
obj.SetActive(false);
if (_pool.ContainsKey(obj.name))
{
_pool[obj.name].Add(obj);
}
else
{
_pool.Add(obj.name, new List<GameObject> { obj });
}
}
}
测试一哈
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestObjPool : MonoBehaviour {
public GameObject[] gameObjects=new GameObject[10];
public void Start()
{
for (int i = 0; i < 10; i++)
{
gameObjects[i]=ObjPool._instance.GetObj("Obj");
}
for (int i = 0; i < 5; i++)
{
ObjPool._instance.RecycleObj(gameObjects[i]);
}
}
}
结果
回收的对象没被销毁只是隐藏了,可以再利用(似乎就是可回收垃圾🤣)
结果
网友评论