1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Events;
  5. /// <summary>
  6. /// 资源加载模块
  7. /// 1.异步加载
  8. /// 2.委托和 lambda表达式
  9. /// 3.协程
  10. /// 4.泛型
  11. /// </summary>
  12. public class ResMgr : BaseManager<ResMgr>
  13. {
  14. //同步加载资源
  15. public T Load<T>(string name) where T:Object
  16. {
  17. T res = Resources.Load<T>(name);
  18. //如果对象是一个GameObject类型的 我把他实例化后 再返回出去 外部 直接使用即可
  19. if (res is GameObject)
  20. return GameObject.Instantiate(res);
  21. else//TextAsset AudioClip
  22. return res;
  23. }
  24. //异步加载资源
  25. public void LoadAsync<T>(string name, UnityAction<T> callback) where T:Object
  26. {
  27. //开启异步加载的协程
  28. MonoMgr.GetInstance().StartCoroutine(ReallyLoadAsync(name, callback));
  29. }
  30. //真正的协同程序函数 用于 开启异步加载对应的资源
  31. private IEnumerator ReallyLoadAsync<T>(string name, UnityAction<T> callback) where T : Object
  32. {
  33. ResourceRequest r = Resources.LoadAsync<T>(name);
  34. yield return r;
  35. if (r.asset is GameObject)
  36. callback(GameObject.Instantiate(r.asset) as T);
  37. else
  38. callback(r.asset as T);
  39. }
  40. }

使用举例

  1. void Update()
  2. {
  3. if (Input.GetMouseButtonDown(0))
  4. {
  5. //PoolMgr.GetInstance().GetObj("Test/Cube");
  6. // 同步加载
  7. GameObject obj = ResMgr.GetInstance().Load<GameObject>("Test/Cube");
  8. obj.transform.localScale = Vector3.one * 2;
  9. }
  10. if (Input.GetMouseButtonDown(1))
  11. {
  12. //PoolMgr.GetInstance().GetObj("Test/Sphere");
  13. ResMgr.GetInstance().LoadAsync<GameObject>("Test/Cube", (obj) =>
  14. {
  15. obj.transform.localScale = Vector3.one * 2;
  16. });
  17. }
  18. }