VersionController.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. using GFGGame.Launcher;
  2. using System.Collections;
  3. using UnityEngine;
  4. using YooAsset;
  5. namespace GFGGame
  6. {
  7. public class VersionController : SingletonMonoBase<VersionController>
  8. {
  9. public const string DefaultPackage = "GameLogic";
  10. /// <summary>
  11. /// 包裹的版本信息
  12. /// </summary>
  13. public string PackageVersion { set; get; }
  14. public void Init()
  15. {
  16. // 初始化资源系统
  17. YooAssets.Initialize();
  18. StartCoroutine(InitVersion());
  19. }
  20. public IEnumerator InitVersion()
  21. {
  22. yield return InitDefaultPackage();
  23. yield return GetStaticVersion(DefaultPackage);
  24. yield return UpdateManifest(DefaultPackage);
  25. CreateDownloader(DefaultPackage);
  26. }
  27. private IEnumerator InitDefaultPackage()
  28. {
  29. // 创建默认的资源包
  30. string packageName = DefaultPackage;
  31. var package = YooAssets.TryGetPackage(packageName);
  32. if (package == null)
  33. {
  34. package = YooAssets.CreatePackage(packageName);
  35. YooAssets.SetDefaultPackage(package);
  36. }
  37. var playMode = GameLauncher.Instance.PlayMode;
  38. InitializationOperation initializationOperation = null;
  39. if (playMode == EPlayMode.EditorSimulateMode)
  40. {
  41. // 编辑器下的模拟模式
  42. var createParameters = new EditorSimulateModeParameters();
  43. createParameters.SimulateManifestFilePath = EditorSimulateModeHelper.SimulateBuild(packageName);
  44. initializationOperation = package.InitializeAsync(createParameters);
  45. }
  46. else if (playMode == EPlayMode.HostPlayMode)
  47. {
  48. // 联机运行模式
  49. string defaultHostServer = GetHostServerURL(DefaultPackage);
  50. string fallbackHostServer = defaultHostServer;
  51. var createParameters = new HostPlayModeParameters();
  52. //createParameters.DecryptionServices = new GameDecryptionServices();
  53. createParameters.QueryServices = new GameQueryServices();
  54. createParameters.RemoteServices = new RemoteServices(defaultHostServer, fallbackHostServer);
  55. initializationOperation = package.InitializeAsync(createParameters);
  56. }
  57. yield return initializationOperation;
  58. if (initializationOperation.Status != EOperationStatus.Succeed)
  59. {
  60. Debug.LogWarning($"{initializationOperation.Error}");
  61. }
  62. }
  63. private IEnumerator GetStaticVersion(string packageName)
  64. {
  65. var package = YooAssets.GetPackage(packageName);
  66. var operation = package.UpdatePackageVersionAsync();
  67. yield return operation;
  68. if (operation.Status == EOperationStatus.Succeed)
  69. {
  70. VersionController.Instance.PackageVersion = operation.PackageVersion;
  71. Debug.Log($"远端最新版本为: {operation.PackageVersion}");
  72. }
  73. else
  74. {
  75. Debug.LogWarning(operation.Error);
  76. }
  77. }
  78. private IEnumerator UpdateManifest(string packageName)
  79. {
  80. bool savePackageVersion = true;
  81. var package = YooAssets.GetPackage(packageName);
  82. var operation = package.UpdatePackageManifestAsync(VersionController.Instance.PackageVersion, savePackageVersion);
  83. yield return operation;
  84. if (operation.Status != EOperationStatus.Succeed)
  85. {
  86. Debug.LogWarning(operation.Error);
  87. Alert.Show("更新版本信息失败,请检测网络链接后重试。")
  88. .SetLeftButton(true, "重试", (data) => { StartCoroutine(UpdateManifest(packageName)); });
  89. }
  90. }
  91. private void CreateDownloader(string packageName)
  92. {
  93. int downloadingMaxNum = 10;
  94. int failedTryAgain = 3;
  95. ResourcePackage package = YooAssets.GetPackage(packageName);
  96. var downloaderOperation = package.CreateResourceDownloader(new string[] { "preload", "dynamic" }, downloadingMaxNum, failedTryAgain);
  97. if (downloaderOperation.TotalDownloadCount == 0)
  98. {
  99. LauncherController.OnVersionCompleted();
  100. }
  101. else
  102. {
  103. //A total of 10 files were found that need to be downloaded
  104. Debug.Log($"Found total {downloaderOperation.TotalDownloadCount} files that need download !");
  105. // 发现新更新文件后,挂起流程系统
  106. // 注意:开发者需要在下载前检测磁盘空间不足
  107. int totalDownloadCount = downloaderOperation.TotalDownloadCount;
  108. long totalDownloadBytes = downloaderOperation.TotalDownloadBytes;
  109. float sizeMB = totalDownloadBytes / 1048576f;
  110. sizeMB = Mathf.Clamp(sizeMB, 0.1f, float.MaxValue);
  111. string totalSizeMB = sizeMB.ToString("f1");
  112. string message = $"游戏有新的内容,{packageName}需要更新{totalSizeMB}MB大小的内容";
  113. Alert.Show(message)
  114. .SetLeftButton(true, "更新", (data) =>
  115. {
  116. StartCoroutine(BeginDownload(downloaderOperation, packageName));
  117. });
  118. }
  119. }
  120. private IEnumerator BeginDownload(ResourceDownloaderOperation downloaderOperation, string packageName)
  121. {
  122. // 注册下载回调
  123. downloaderOperation.OnDownloadErrorCallback =
  124. (fileName, error) =>
  125. {
  126. Debug.LogError($"加载{fileName}失败 {error}");
  127. };
  128. downloaderOperation.OnDownloadProgressCallback =
  129. (totalDownloadCount, currentDownloadCount, totalDownloadSizeBytes, currentDownloadSizeBytes) =>
  130. {
  131. string currentSizeMB = (currentDownloadSizeBytes / 1048576f).ToString("f1");
  132. string totalSizeMB = (totalDownloadSizeBytes / 1048576f).ToString("f1");
  133. var progress = currentDownloadSizeBytes / totalDownloadSizeBytes;
  134. LauncherView.Instance.SetDesc($"正在下载资源,{currentDownloadCount}/{totalDownloadCount}", $"{currentSizeMB}MB/{totalSizeMB}MB", true);
  135. LauncherView.Instance.SetProgress((int)(progress * 100));
  136. };
  137. downloaderOperation.BeginDownload();
  138. yield return downloaderOperation;
  139. // 检测下载结果
  140. if (downloaderOperation.Status != EOperationStatus.Succeed)
  141. {
  142. Alert.Show("下载失败!请检查网络状态后重试。")
  143. .SetLeftButton(true, "重试", (data) =>
  144. {
  145. StartCoroutine(BeginDownload(downloaderOperation, packageName));
  146. });
  147. yield break;
  148. }
  149. LauncherController.OnVersionCompleted();
  150. }
  151. /// <summary>
  152. /// 获取资源服务器地址
  153. /// </summary>
  154. private string GetHostServerURL(string packageName)
  155. {
  156. string hostServerIP = "http://10.108.64.127";
  157. #if UNITY_EDITOR
  158. if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.Android)
  159. return $"{hostServerIP}/CDN/Android/{packageName}";
  160. else if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.iOS)
  161. return $"{hostServerIP}/CDN/IPhone/{packageName}";
  162. else if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.WebGL)
  163. return $"{hostServerIP}/CDN/WebGL/{packageName}";
  164. else
  165. return $"{hostServerIP}/CDN/PC/{packageName}";
  166. #else
  167. if (Application.platform == RuntimePlatform.Android)
  168. return $"{hostServerIP}/CDN/Android/{packageName}";
  169. else if (Application.platform == RuntimePlatform.IPhonePlayer)
  170. return $"{hostServerIP}/CDN/IPhone/{packageName}";
  171. else if (Application.platform == RuntimePlatform.WebGLPlayer)
  172. return $"{hostServerIP}/CDN/WebGL/{packageName}";
  173. else
  174. return $"{hostServerIP}/CDN/PC/{packageName}";
  175. #endif
  176. }
  177. /// <summary>
  178. /// 远端资源地址查询服务类
  179. /// </summary>
  180. private class RemoteServices : IRemoteServices
  181. {
  182. private readonly string _defaultHostServer;
  183. private readonly string _fallbackHostServer;
  184. public RemoteServices(string defaultHostServer, string fallbackHostServer)
  185. {
  186. _defaultHostServer = defaultHostServer;
  187. _fallbackHostServer = fallbackHostServer;
  188. }
  189. string IRemoteServices.GetRemoteMainURL(string fileName)
  190. {
  191. return $"{_defaultHostServer}/{fileName}";
  192. }
  193. string IRemoteServices.GetRemoteFallbackURL(string fileName)
  194. {
  195. return $"{_fallbackHostServer}/{fileName}";
  196. }
  197. }
  198. }
  199. }