LoadModelAB.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6. using UnityEngine.UI;
  7. public class LoadModelAB : MonoBehaviour
  8. {
  9. public List<string> strlist;
  10. public GameObject loadtext;
  11. public static Dictionary<string,GameObject> ModelDic = new Dictionary<string, GameObject>();
  12. // Start is called before the first frame update
  13. void Start()
  14. {
  15. for (int i = 0;i<strlist.Count;i++)
  16. {
  17. StartCoroutine(LoadAB(strlist[i]));
  18. }
  19. }
  20. IEnumerator LoadAB(string assetBundleName)
  21. {
  22. AssetBundle ab =null;
  23. string filePath = System.IO.Path.Combine(Application.streamingAssetsPath + "/bd", assetBundleName);
  24. #if UNITY_EDITOR_OSX
  25. AssetBundleCreateRequest assetBundle = AssetBundle.LoadFromFileAsync(filePath);
  26. yield return assetBundle;
  27. ab = assetBundle.assetBundle;
  28. // 加载AssetBundle
  29. #else
  30. UnityWebRequest req = UnityWebRequestAssetBundle.GetAssetBundle(filePath);
  31. yield return req.SendWebRequest();
  32. if (req.error == null)
  33. {
  34. ab = (req.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
  35. }
  36. else
  37. {
  38. loadtext.GetComponent<Text>().text=req.error;
  39. }
  40. #endif
  41. if(ab)
  42. {
  43. AssetBundleRequest abr =ab.LoadAssetAsync<GameObject>(assetBundleName);
  44. yield return abr;
  45. GameObject Model = GameObject.Instantiate((GameObject)abr.asset);
  46. Model.transform.SetParent(this.transform);
  47. Model.transform.localEulerAngles = Vector3.zero;
  48. Model.transform.localPosition = Vector3.zero;
  49. Model.transform.localScale = Vector3.one;
  50. Model.name = assetBundleName+"_Model";
  51. ModelDic.Add(assetBundleName,Model);
  52. loadtext.SetActive(false);
  53. }
  54. }
  55. // Update is called once per frame
  56. void Update()
  57. {
  58. }
  59. }