一、资源文件位置
位于Resource文件夹下。Resource文件夹的位置没有强制约束。
二、加载Resource文件
1、同步加载文件
//path:不包含拓展名
Resources.Load(path);
2、异步加载文件
ResourceRequest request = Resources.LoadAsync<T>(path);
yield return request;
三、代码
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Events;
using Net.Realmoon.Singleton;
using Net.Realmoon.Mono;
namespace Net.Realmoon.IO.Resource
{
/// <summary>
/// resource工具类
/// </summary>
public class ResourceLoadTools : SingletonBase<ResourceLoadTools>
{
private Dictionary<string, GameObject> cacheMap;
protected override void Init()
{
base.Init();
cacheMap = new Dictionary<string, GameObject>();
}
#region 同步加载
/// <summary>
/// 同步加载资源
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public Object Load(string path)
{
Object res = Resources.Load(path);
//gameobject 实例化后再返回
if (res is GameObject)
{
return GameObject.Instantiate(res);
}
else
{
//不需要实例化的对象
return res;
}
}
/// <summary>
/// 同步加载资源
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public Object Load(string path, System.Type type)
{
Object res = Resources.Load(path, type);
//gameobject 实例化后再返回
if (res is GameObject)
{
return GameObject.Instantiate(res);
}
else
{
Debug.Log("同步加载了");
//不需要实例化的对象
return res;
}
}
//同步加载资源
public T Load<T>(string path, bool isCreateGameObject = true) where T : Object
{
T res = Resources.Load<T>(path);
//gameobject 实例化后再返回
if (res is GameObject && isCreateGameObject)
{
return GameObject.Instantiate(res);
}
else
{
//不需要实例化的对象
return res;
}
}
//同步加载资源
public T Load<T>(string path, Transform parent) where T : Object
{
T res = Resources.Load<T>(path);
//gameobject 实例化后再返回
if (res is GameObject)
{
return GameObject.Instantiate(res, parent);
}
else
{
//不需要实例化的对象
return res;
}
}
/// <summary>
/// 读取Resource中的文件
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public string ReadResourceFile(string path)
{
TextAsset ta = Resources.Load<TextAsset>(path);
if (ta != null)
{
return ta.text;
}
else
{
return "";
}
}
#endregion
//资源异步加载
public void LoadAsync<T>(string path, UnityAction<T> callback) where T : Object
{
MonoTools.Instance.StartCoroutine(ReallyLoadAsync<T>(path, callback));
}
private IEnumerator ReallyLoadAsync<T>(string path, UnityAction<T> callback) where T : Object
{
ResourceRequest request = Resources.LoadAsync<T>(path);
yield return request;
if (request.asset is GameObject)
{
callback(GameObject.Instantiate(request.asset) as T);
}
else
{
callback(request.asset as T);
}
}
}
}
留言