AssetLoadHelper.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6. public class AssetLoadHelper : MonoBehaviour
  7. {
  8. public static AssetLoadHelper _Instance;
  9. private Dictionary<string, AssetBundle> abRes_Dir;
  10. string[] resList = { "weathertool", "model" };
  11. public bool isLoad
  12. {
  13. get
  14. {
  15. for (int i = 0; i < resList.Length; i++)
  16. {
  17. if (!abRes_Dir.ContainsKey(resList[i]))
  18. {
  19. return false;
  20. }
  21. }
  22. return true;
  23. }
  24. }
  25. private void Awake()
  26. {
  27. _Instance = this;
  28. LoadAB_res();
  29. }
  30. private void LoadAB_res()
  31. {
  32. abRes_Dir = new Dictionary<string, AssetBundle>();
  33. foreach (var t in resList)
  34. {
  35. StartCoroutine(LoadAB(t));
  36. }
  37. }
  38. IEnumerator LoadAB(string _name)
  39. {
  40. string abPath = "/AB/";
  41. if (Application.isEditor) {
  42. abPath = "/ABW/";
  43. }
  44. UnityWebRequest www =
  45. UnityWebRequestAssetBundle.GetAssetBundle(Application.streamingAssetsPath + abPath + _name);
  46. yield return www.SendWebRequest();
  47. if (www.result != UnityWebRequest.Result.Success)
  48. {
  49. Debug.LogError(www.result);
  50. }
  51. else
  52. {
  53. AssetBundle ab= DownloadHandlerAssetBundle.GetContent(www);
  54. if (ab != null)
  55. {
  56. abRes_Dir.TryAdd(_name, ab);
  57. }
  58. }
  59. www.Dispose();
  60. }
  61. public T LoadAssets<T>(string abName, string resName) where T : UnityEngine.Object
  62. {
  63. T obj = null;
  64. if (!abRes_Dir.ContainsKey(abName))
  65. {
  66. Debug.LogError($"{abName}丢失");
  67. }
  68. else
  69. {
  70. if (typeof(T) == typeof(GameObject))
  71. {
  72. obj = Instantiate(abRes_Dir[abName].LoadAsset<T>(resName));
  73. }
  74. else
  75. {
  76. obj = abRes_Dir[abName].LoadAsset<T>(resName);
  77. }
  78. }
  79. return obj;
  80. }
  81. }