当前位置: 移动技术网 > IT编程>开发语言>c# > unity使用字典动态查找和删除对象池

unity使用字典动态查找和删除对象池

2020年08月01日  | 移动技术网IT编程  | 我要评论
今天我给大家用字典实现一下对象池,可以动态和定向的添加和删除池中的物体,然后就给出代码了哈。

今天我给大家用字典实现一下对象池,可以动态和定向的添加和删除池中的物体

然后就给出代码了哈

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");
        }
    }

}

然后给大家看一下代码中运行的样子

在这里插入图片描述
连名字我都自动根据传入的参数修改了 是不是很贴心呀

希望这篇博客对大家有帮助 

本文地址:https://blog.csdn.net/weixin_44302602/article/details/108256507

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网