今天我给大家用字典实现一下对象池,可以动态和定向的添加和删除池中的物体
然后就给出代码了哈
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using UnityEngine;
public class GameObjectPool : MonoBehaviour
{
public Dictionary<string, List<GameObject>> PoolDic = new Dictionary<string, List<GameObject>>();
private int poolsize = 10;//初始化池子大小
public static GameObjectPool Instance;//单例模式
private void Start()
{
Init();
}
/// <summary>
///初始化
/// </summary>
private void Init()
{
Instance = this;
GetGroup("Cube");
GetGroup("Sphere");
}
private void GetGroup(string name)
{
GameObject group = new GameObject();
group.name = name + "Group";
List<GameObject> Objects = new List<GameObject>();//实例化一个list
for(int i = 0; i < poolsize; i++)
{
GetGameObject(name, group, Objects);
}
PoolDic.Add(name + "Group", Objects);//添加到字典中去
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="父物体"></param>
/// <param name="池子"></param>
public void GetGameObject(string name ,GameObject father,List<GameObject > pool)
{
GameObject InsObj= Instantiate(Resources.Load<GameObject>(name), new Vector3(0, 0, 0), Quaternion.identity);
InsObj.name = name;
//实例化出来
InsObj.transform.SetParent(father.transform);
//设置父物体
InsObj.SetActive(false);
pool.Add(InsObj);//为池子添加对象
}
public GameObject Active(string name)
{
name += "Group";
if (!PoolDic.ContainsKey(name))
{
//不包含这个群组
Debug.LogError("不包含群组");
}
else
{
for (int i = 0; i < poolsize; i++)
{
//当这个对象不是出于激活状态的时候
if (!PoolDic[name][i].activeSelf)
{
PoolDic[name][i].SetActive(true);//显示
return PoolDic[name][i];
}
}
}
return null;
}
//private T AddAndGetCom<T>(GameObject obj) where T:Component
//{
// if (obj.GetComponent < T >()== null)
// {
// obj.AddComponent<T>();
// }
// return obj.GetComponent<T>();
//}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Active("Cube");
}
}
}
然后给大家看一下代码中运行的样子

连名字我都自动根据传入的参数修改了 是不是很贴心呀
希望这篇博客对大家有帮助
本文地址:http://www.51sjk.com/Upload/Articles/1/0/259/259730_20210701002233031.jpg
狠不下心28213228