LoadDll.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Threading.Tasks;
  8. using UnityEngine;
  9. using UnityEngine.Networking;
  10. using LitJson;
  11. using TMPro;
  12. using UnityEngine.UI;
  13. public class LoadDll : MonoBehaviour
  14. {
  15. public GameObject EditorGame;
  16. static LoadDll instance;
  17. private void Awake()
  18. {
  19. instance = this;
  20. }
  21. void Start()
  22. {
  23. this.transform.SetParent(OpenXRCamera.Instance.head.transform);
  24. this.transform.localPosition = Vector3.zero;
  25. this.transform.localEulerAngles = Vector3.zero;
  26. //PlayerPrefs.DeleteAll();
  27. #if ISLOCAL
  28. EditorGame.SetActive(true);
  29. this.gameObject.SetActive(false);
  30. #else
  31. StartCoroutine(DownLoadAssets());
  32. #endif
  33. }
  34. private static Dictionary<string, byte[]> s_assetDatas = new Dictionary<string, byte[]>();
  35. public static byte[] ReadBytesFromStreamingAssets(string dllName)
  36. {
  37. return s_assetDatas[dllName];
  38. }
  39. private string GetWebRequestPath(string asset)
  40. {
  41. var path = $"{Application.streamingAssetsPath}/{asset}";
  42. if (!path.Contains("://"))
  43. {
  44. path = "file://" + path;
  45. }
  46. return path;
  47. }
  48. private static List<string> AOTMetaAssemblyFiles { get; } = new List<string>()
  49. {
  50. "mscorlib.dll.bytes",
  51. "System.dll.bytes",
  52. "System.Core.dll.bytes",
  53. "UniTask.dll.bytes",
  54. "Minio.dll.bytes",
  55. "COSXML.dll.bytes",
  56. "System.Runtime.CompilerServices.Unsafe.dll.bytes"
  57. };
  58. public Text text;
  59. public Text text2;
  60. public Slider slider;
  61. string HotUpdateScripts = "HotUpdateScripts";
  62. string HotUpdateAssets = "HotUpdateAssets";
  63. IEnumerator DownLoadAssets()
  64. {
  65. text.text = "正在获取网关数据";
  66. for (int i = 0; i < AOTMetaAssemblyFiles.Count; i++)
  67. {
  68. yield return DownLoadLocal(AOTMetaAssemblyFiles[i]);
  69. }
  70. slider.gameObject.SetActive(false);
  71. while (HttpSDKAction.Instance.jsonData==null || HttpSDKAction.Instance.jsonData=="")
  72. {
  73. yield return null;
  74. }
  75. JsonData data = new JsonData();
  76. string scUrl = "";
  77. string artUrl = "";
  78. try
  79. {
  80. data = JsonMapper.ToObject(HttpSDKAction.Instance.jsonData);
  81. scUrl = data[HotUpdateScripts].ToString();
  82. artUrl = data[HotUpdateAssets].ToString();
  83. }
  84. catch
  85. {
  86. }
  87. if(scUrl != "")
  88. {
  89. if (!bool.Parse(data["isHotUpdate"].ToString()))
  90. {
  91. text.text = "正在下载代码";
  92. yield return DownLoadAssets(scUrl, HotUpdateScripts, false);
  93. text.text = "正在下载配置";
  94. yield return DownLoadAssets(artUrl, HotUpdateAssets, false);
  95. }
  96. else if (PlayerPrefs.GetString("HotUpdateVersion") == data["HotUpdateVersion"].ToString())
  97. {
  98. text.text = "正在编译代码";
  99. string filePath = PlayerPrefs.GetString(HotUpdateScripts);
  100. Task<byte[]> Tb = File.ReadAllBytesAsync(filePath);
  101. yield return Tb;
  102. slider.gameObject.SetActive(false);
  103. Assembly.Load(Tb.Result);
  104. text.text = "正在解析配置";
  105. filePath = PlayerPrefs.GetString(HotUpdateAssets);
  106. Task<byte[]> Tb2 = File.ReadAllBytesAsync(filePath);
  107. yield return Tb2;
  108. text.text = "正在解析配置";
  109. slider.gameObject.SetActive(false);
  110. AssetBundleCreateRequest acr = AssetBundle.LoadFromMemoryAsync(Tb2.Result);
  111. while (!acr.isDone)
  112. {
  113. text2.text = (acr.progress*100).ToString("F2") + "%";
  114. slider.value = float.Parse((acr.progress ).ToString("F2"));
  115. yield return null;
  116. }
  117. slider.gameObject.SetActive(true);
  118. AssetBundleRequest abr = acr.assetBundle.LoadAssetAsync<GameObject>("LocalAsset");
  119. text.text = "正在加载配置";
  120. while (!abr.isDone)
  121. {
  122. text2.text = (abr.progress * 100).ToString("F2") + "%";
  123. slider.value = float.Parse((abr.progress ).ToString("F2"));
  124. yield return null;
  125. }
  126. copyGameObject(abr.asset);
  127. this.gameObject.SetActive(false);
  128. }
  129. else
  130. {
  131. text.text = "正在下载代码";
  132. yield return DownLoadAssets(scUrl, HotUpdateScripts);
  133. text.text = "正在下载配置";
  134. yield return DownLoadAssets(artUrl, HotUpdateAssets);
  135. }
  136. }
  137. else
  138. {
  139. text.text = "正在下载代码";
  140. yield return DownLoadAssets(scUrl, HotUpdateScripts, false);
  141. text.text = "正在下载配置";
  142. yield return DownLoadAssets(artUrl, HotUpdateAssets, false);
  143. }
  144. }
  145. public IEnumerator DownLoadLocal(string name)
  146. {
  147. slider.gameObject.SetActive(true);
  148. UnityWebRequest www = UnityWebRequest.Get(GetWebRequestPath(name));
  149. www.SendWebRequest();
  150. while (!www.isDone)
  151. {
  152. text2.text = (www.downloadProgress * 100).ToString("F2") + "%";
  153. slider.value = float.Parse((www.downloadProgress).ToString("F2"));
  154. yield return null;
  155. }
  156. #if UNITY_2020_1_OR_NEWER
  157. if (www.result != UnityWebRequest.Result.Success)
  158. {
  159. Debug.Log(www.error);
  160. }
  161. #else
  162. if (www.isHttpError || www.isNetworkError)
  163. {
  164. Debug.Log(www.error);
  165. }
  166. #endif
  167. }
  168. public IEnumerator DownLoadAssets(string dllPath,string name,bool isRemote=true)
  169. {
  170. slider.gameObject.SetActive(true);
  171. if(!isRemote)
  172. {
  173. dllPath = GetWebRequestPath(name);
  174. }
  175. UnityWebRequest www = UnityWebRequest.Get(dllPath);
  176. www.SendWebRequest();
  177. while (!www.isDone)
  178. {
  179. text2.text = (www.downloadProgress * 100).ToString("F2") + "%";
  180. slider.value = float.Parse((www.downloadProgress ).ToString("F2"));
  181. yield return null;
  182. }
  183. #if UNITY_2020_1_OR_NEWER
  184. if (www.result != UnityWebRequest.Result.Success)
  185. {
  186. Debug.Log(www.error);
  187. }
  188. #else
  189. if (www.isHttpError || www.isNetworkError)
  190. {
  191. Debug.Log(www.error);
  192. }
  193. #endif
  194. else
  195. {
  196. if(name == HotUpdateScripts)
  197. {
  198. text.text = "正在编译代码";
  199. slider.gameObject.SetActive(false);
  200. Assembly.Load(www.downloadHandler.data);
  201. string fileName = HotUpdateScripts;
  202. if (!Directory.Exists(Application.persistentDataPath + "/HotUpdate"))
  203. Directory.CreateDirectory(Application.persistentDataPath + "/HotUpdate" );
  204. string filePathname = Application.persistentDataPath + "/HotUpdate/" + fileName;
  205. // if (File.Exists(filePathname))
  206. // File.Delete(filePathname);
  207. File.WriteAllBytes(filePathname, www.downloadHandler.data);
  208. PlayerPrefs.SetString(HotUpdateScripts, filePathname);
  209. }
  210. else
  211. {
  212. text.text = "正在解析配置";
  213. slider.gameObject.SetActive(false);
  214. AssetBundleCreateRequest acr = AssetBundle.LoadFromMemoryAsync(www.downloadHandler.data);
  215. while (!acr.isDone)
  216. {
  217. text2.text = (acr.progress * 100).ToString("F2") + "%";
  218. slider.value = float.Parse((acr.progress ).ToString("F2"));
  219. yield return null;
  220. }
  221. slider.gameObject.SetActive(true);
  222. AssetBundleRequest abr = acr.assetBundle.LoadAssetAsync<GameObject>("LocalAsset");
  223. text.text = "正在加载配置";
  224. while (!abr.isDone)
  225. {
  226. text2.text = (abr.progress * 100).ToString("F2") + "%";
  227. slider.value = float.Parse((abr.progress ).ToString("F2"));
  228. yield return null;
  229. }
  230. copyGameObject(abr.asset);
  231. this.gameObject.SetActive(false);
  232. string fileName = HotUpdateAssets;
  233. if (!Directory.Exists(Application.persistentDataPath + "/HotUpdate"))
  234. Directory.CreateDirectory(Application.persistentDataPath + "/HotUpdate");
  235. string filePathname = Application.persistentDataPath + "/HotUpdate/" + fileName;
  236. // if (File.Exists(filePathname))
  237. // File.Delete(filePathname);
  238. File.WriteAllBytes(filePathname, www.downloadHandler.data);
  239. PlayerPrefs.SetString(HotUpdateAssets, filePathname);
  240. }
  241. }
  242. }
  243. void copyGameObject(UnityEngine.Object o)
  244. {
  245. Instantiate(o);
  246. }
  247. private static Assembly _hotUpdateAss;
  248. /// <summary>
  249. /// 为aot assembly加载原始metadata, 这个代码放aot或者热更新都行。
  250. /// 一旦加载后,如果AOT泛型函数对应native实现不存在,则自动替换为解释模式执行
  251. /// </summary>
  252. private static void LoadMetadataForAOTAssemblies()
  253. {
  254. }
  255. void StartGame()
  256. {
  257. // LoadMetadataForAOTAssemblies();
  258. /*
  259. #if !UNITY_EDITOR
  260. _hotUpdateAss = Assembly.Load(ReadBytesFromStreamingAssets("HotUpdate.dll.bytes"));
  261. #else
  262. _hotUpdateAss = System.AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == "HotUpdate");
  263. #endif
  264. */
  265. // Type entryType = _hotUpdateAss.GetType("Entry");
  266. // entryType.GetMethod("Start").Invoke(null, null);
  267. }
  268. }