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