Unity泛型 Resources.LoadAll<T>并以名称存为字典

Resources.LoadAll < T > ( ) 这里的T的类型限制在Object内

虽然Unity的同一个文件夹下, 不允许出现相同名字的2个东西(除非后缀不同), 但是LoadAll方法会Load所有子文件夹, 所以有重名的风险, 所以需要判断一下字典中是否已经包含

    /// <summary>
    /// 从Resources中得到T类型的东西并以名称存为字典
    /// </summary>
    public static Dictionary<string, T> GetResourcesDic<T>(string path) where T : UnityEngine.Object
    {
        Dictionary<string, T> dic = new Dictionary<string, T>();

        T[] array = Resources.LoadAll<T>(path);
        for (int i = 0; i < array.Length; i++)
        {
            string key = array[i].name;
            if (!dic.ContainsKey(key))
            {
                dic.Add(key, array[i]);
            }
            else
            {
                Debug.LogError(key + " 在 " + path + " 中重复了");
            }
        }

        return dic;
    }

读取Resources下的Prefabs的工具类


using System.Collections.Generic;
using UnityEngine;

public class PrefabsLoader
{
    /// <summary>
    /// 从Resources中得到单个T
    /// </summary>
    public static T GetPrefab<T>(string path) where T : Object
    {
        T prefab = Resources.Load<T>(path);
        if (prefab == null)
        {
            Debug.LogError("找不到: " + path);
        }
        return prefab;
    }

    /// <summary>
    /// 从Resources中得到T, 并存为数组
    /// </summary>
    public static T[] GetPrefabs<T>(string path) where T : Object
    {
        T[] prefabs = Resources.LoadAll<T>(path);
        if (prefabs.Length == 0)
        {
            Debug.LogError("找不到: " + path);
        }
        return prefabs;
    }

    /// <summary>
    /// 从Resources中得到T, 并存为列表
    /// </summary>
    public static List<T> GetPrefabsList<T>(string path) where T : Object
    {
        T[] prefabs = GetPrefabs<T>(path);

        List<T> list = new List<T>();
        for (int i = 0; i < prefabs.Length; i++)
        {
            list.Add(prefabs[i]);
        }
        return list;
    }

    /// <summary>
    /// 从Resources中得到T, 并以名称存为字典
    /// </summary>
    public static Dictionary<string, T> GetPrefabsDic<T>(string path) where T : Object
    {
        T[] prefabs = GetPrefabs<T>(path);

        Dictionary<string, T> dic = new Dictionary<string, T>();
        for (int i = 0; i < prefabs.Length; i++)
        {
            string key = prefabs[i].name;
            if (!dic.ContainsKey(key))
            {
                dic.Add(key, prefabs[i]);
            }
            else
            {
                Debug.LogError(key + " 在 " + path + " 中重复了");
            }
        }
        return dic;
    }
}


  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值