Unity资源管理封装【同步加载、异步加载】
1、使用场景:
对特定资源加载选择同步或是异步加载方式
2、实现思路:
对GameObject类型的资源 在加载的时候进行实例化,直接返回
3、具体实现:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; /// <summary> /// 资源加载 单例 /// </summary> public class ResController : SingletonBase<ResController> { //同步加载资源 public T LoadAsset<T>(string name) where T:Object { //加载资源 T res=Resources.Load<T>(name); if (res is GameObject) return GameObject.Instantiate(res);//如果是GameObject 类型的先实例化再返回该对象 else return res;//如果是 TextAsset、AudioClip 等类型的资源文件 则直接返回 } //异步加载资源 public void LoadAssetAsync<T>(string name, UnityAction<T> callBack) where T : Object { //使用自己封装的Mono开启协程 MonoMgr.GetInstance().StartCoroutine(realLoadAssetAysnc(name,callBack)); } //真正的异步加载 private IEnumerator realLoadAssetAysnc<T>(string name,UnityAction<T> callBack) where T:Object { ResourceRequest res = Resources.LoadAsync<T>(name); yield return res; if (res.asset is GameObject) callBack(GameObject.Instantiate(res.asset) as T); else callBack(res.asset as T); } }
测试使用:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameStart : MonoBehaviour { void Update() { if (Input.GetMouseButtonDown(0)) { GameObject obj=ResController.GetInstance().LoadAsset<GameObject>("Pool/Cube"); obj.transform.localScale = Vector3.one * 2; } if (Input.GetMouseButtonDown(1)) { ResController.GetInstance().LoadAssetAsync<GameObject>("Pool/Cube2", (obj) => { obj.transform.localScale = Vector3.one * 2; }); } } }
评论