LoadModelAB.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. StartCoroutine(Downloadab());
  16. }
  17. IEnumerator Downloadab()
  18. {
  19. while (DeMaDataManager.ip=="")
  20. {
  21. yield return null;
  22. }
  23. while (DeMaDataManager.token=="")
  24. {
  25. yield return null;
  26. }
  27. yield return new WaitForSeconds(1f);
  28. for (int i = 0;i<strlist.Count;i++)
  29. {
  30. yield return StartCoroutine(LoadAB(strlist[i]));
  31. }
  32. loadtext.SetActive(false);
  33. }
  34. IEnumerator LoadAB(string assetBundleName)
  35. {
  36. AssetBundle ab =null;
  37. string filePath = System.IO.Path.Combine(Application.streamingAssetsPath + "/bd", assetBundleName);
  38. #if UNITY_EDITOR_OSX
  39. AssetBundleCreateRequest assetBundle = AssetBundle.LoadFromFileAsync(filePath);
  40. yield return assetBundle;
  41. ab = assetBundle.assetBundle;
  42. // 加载AssetBundle
  43. #else
  44. UnityWebRequest req = UnityWebRequestAssetBundle.GetAssetBundle(filePath);
  45. yield return req.SendWebRequest();
  46. if (req.error == null)
  47. {
  48. ab = (req.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
  49. }
  50. else
  51. {
  52. loadtext.GetComponent<Text>().text=req.error;
  53. }
  54. #endif
  55. if(ab)
  56. {
  57. AssetBundleRequest abr =ab.LoadAssetAsync<GameObject>(assetBundleName);
  58. yield return abr;
  59. GameObject Model = GameObject.Instantiate((GameObject)abr.asset);
  60. Model.transform.SetParent(this.transform);
  61. Model.transform.localEulerAngles = Vector3.zero;
  62. Model.transform.localPosition = Vector3.zero;
  63. Model.transform.localScale = Vector3.one;
  64. Model.name = assetBundleName+"_Model";
  65. ModelDic.Add(assetBundleName,Model);
  66. }
  67. }
  68. // Update is called once per frame
  69. void Update()
  70. {
  71. }
  72. }