对象池的使用(借鉴大神,仅作为笔记用)

对象池

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool
{
private static ObjectPool instance;
/// <summary>
/// 对象池,字典中与key值对应的是数组(arraylist)(例:key为手枪子弹 对应arraylist[手枪子弹,手枪子弹,手枪子弹。。。。。。 ])。
/// </summary>
private Dictionary<string, List<GameObject>> Pool;
/// <summary>
/// 预设体
/// </summary>
private Dictionary<string, GameObject> Prefabs;
//结构函数
private ObjectPool()
{
Pool = new Dictionary<string, List<GameObject>>();
Prefabs = new Dictionary<string, GameObject>();
}
#region 单例
public static ObjectPool GetInstance()
{
if (instance == null)
{
instance = new ObjectPool();
}
return instance;
}
#endregion
/// <summary>
/// 从对象池中获取对象
/// </summary>
/// <param name="objName"></param>
/// <returns></returns>
public GameObject GetObj(string objName)
{
GameObject result = null;
//判断是否有该名字的对象池 //对象池中有对象
if (Pool.ContainsKey(objName) && Pool[objName].Count > 0)
{
//获取这个对象池中的第一个对象
result = Pool[objName][0];
//激活对象
result.SetActive(true);
//从对象池中移除对象
Pool[objName].Remove(result);
//返回结果
return result;
}
//如果没有该名字的对象池或者该名字对象池没有对象
GameObject Prefab = null;
if (Prefabs.ContainsKey(objName)) //如果已经加载过预设体
{
Prefab = Prefabs[objName];
}
else //如果没有加载过预设体
{
//加载预设体
Prefab = Resources.Load<GameObject>("Obj/" + objName);
//更新预设体的字典
Prefabs.Add(objName, Prefab);
}
//实例化物体
result = UnityEngine.Object.Instantiate(Prefab);
//改名 去除Clone
result.name = objName;
return result;
}
/// <summary>
/// 回收对象到对象池
/// </summary>
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 Bullet : MonoBehaviour
{
public void OnEnable()
{
StartCoroutine(AutoRecycle());
}
//3秒后自动回收到对象池
IEnumerator AutoRecycle()
{
yield return new WaitForSeconds(3f);
ObjectPool.GetInstance().RecycleObj(this.gameObject);
}
}
用来使用对象池(调用)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class test : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
ObjectPool.GetInstance().GetObj("Bullet");
}
}
}

 



posted @ 2019-10-29 14:52  C#初学者—Damon  阅读(605)  评论(0编辑  收藏  举报