为了方便程序中动态加载resources目录中物体,编写了一个ResourceManager的单例类,使用时需要将其附加到一个游戏物体上。
可以实现对物体的分类、重命名、异步加载。
可用方法如下:
//通过名字和类型加载,类型为0时,不判断类型
ResourceRes<T> Load<T>(string name, ResourceType type = 0) where T : UnityEngine.Object
//通过名字和类型加载所有,类型为0时,不判断类型
T[] LoadAll<T>(string name, ResourceType type = 0) where T : UnityEngine.Object
//通过类型加载所有,可以用与的方式,例如加载两个类型:(ResourceType.BGM|ResourceType.Model)
ResourceRes<T>[] LoadAllFromTypeMask<T>(int typeMask) where T : UnityEngine.Object
//异步通过类型加载所有
public void LoadAllFromTypeMaskAsync<T>(int typeMask, Action<ResourceRes<T>[]> onComplete) where T : UnityEngine.Object
//异步通过名字和类型加载所有
void LoadAsync<T>(string name, Action<ResourceRes<T>> onComplete, ResourceType type = 0) where T : UnityEngine.Object
使用方式:
GameObject obj = ResourceManager.Instance.Load<GameObject>("Main").res;
ResourceManager.Instance.LoadAsync<GameObject>("Main", (res) =>
{
if (res != null)
{
GameObject obj = res.res;
}
});
源码如下:
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
using System.IO;
#endif
public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
private static T _Instance;
public static T Instance
{
get
{
if (_Instance == null)
{
_Instance = FindObjectOfType<T>();
}
return _Instance;
}
}
}
//物体分类,一个物体可以是多种类型
public enum ResourceType
{
BGM = 0x0001,
Model = 0x0002,
Scene = 0x0004,
PromptAudio = 0x0008,
}
[System.Serializable]
public class ResourceItem
{
public string name;//资源名字
public string path;//资源resources路径
public ResourceType type;//资源类型
public ResourceItem(string name, string path, ResourceType type)
{
this.name = name;
this.path = path;
this.type = type;
}
}
[Serializable]
public class ResourceRes<T> where T : UnityEngine.Object
{
public string