VersionController.cs 9.4 KB

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