From b768474e6755ff0022507bf85336494ae309a356 Mon Sep 17 00:00:00 2001 From: changyunjia <905640960@qq.com> Date: Fri, 12 Jun 2026 17:14:59 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...onfigs.meta => AddressableAssetsData.meta} | 2 +- .../AddressableAssetSettings.asset | 110 ++++++++++ .../AddressableAssetSettings.asset.meta | 8 + Assets/AddressableAssetsData/Android.meta | 8 + .../Android/addressables_content_state.bin | Bin 0 -> 1454 bytes .../addressables_content_state.bin.meta | 7 + .../AssetGroupTemplates.meta | 8 + .../AssetGroupTemplates/Packed Assets.asset | 76 +++++++ .../Packed Assets.asset.meta | 8 + Assets/AddressableAssetsData/AssetGroups.meta | 8 + .../AssetGroups/Built In Data.asset | 23 +++ .../AssetGroups/Built In Data.asset.meta | 8 + .../AssetGroups/Default Local Group.asset | 31 +++ .../Default Local Group.asset.meta | 8 + .../AssetGroups/Schemas.meta | 8 + .../Built In Data_PlayerDataGroupSchema.asset | 17 ++ ...t In Data_PlayerDataGroupSchema.asset.meta | 8 + ... Local Group_BundledAssetGroupSchema.asset | 45 ++++ ...l Group_BundledAssetGroupSchema.asset.meta | 8 + ...Local Group_ContentUpdateGroupSchema.asset | 16 ++ ... Group_ContentUpdateGroupSchema.asset.meta | 8 + .../AddressableAssetsData/DataBuilders.meta | 8 + .../DataBuilders/BuildScriptFastMode.asset | 20 ++ .../BuildScriptFastMode.asset.meta | 8 + .../DataBuilders/BuildScriptPackedMode.asset | 20 ++ .../BuildScriptPackedMode.asset.meta | 8 + .../BuildScriptPackedPlayMode.asset | 20 ++ .../BuildScriptPackedPlayMode.asset.meta | 8 + .../DataBuilders/BuildScriptVirtualMode.asset | 20 ++ .../BuildScriptVirtualMode.asset.meta | 8 + .../AddressableAssetsData/DefaultObject.asset | 15 ++ .../DefaultObject.asset.meta | 8 + .../ProfileDataSourceSettings.asset | 34 +++ .../ProfileDataSourceSettings.asset.meta | 8 + Assets/AddressableAssetsData/iOS.meta | 8 + .../iOS/addressables_content_state.bin | Bin 0 -> 1450 bytes .../iOS/addressables_content_state.bin.meta | 7 + Assets/Configs.meta | 2 +- .../public_conf_1765185287.json} | 0 .../public_conf_1765185287.json.meta} | 2 +- Assets/Resources/GameConfig.asset | 2 +- Assets/Resources/NetworkConfig.asset | 2 +- .../SGModule/Editor/AddressablesManager.cs | 188 +++++++++++++++++ .../Editor/AddressablesManager.cs.meta | 3 + .../Scripts/ConfigLoader/ConfigFileManager.cs | 185 +++++------------ .../ConfigLoader/FileNetworkManager.cs | 195 ++++++------------ .../Net/SGModule/Scripts/Core/NetChecker.cs | 170 ++++++--------- Packages/manifest.json | 1 + Packages/packages-lock.json | 21 ++ ProjectSettings/GvhProjectSettings.xml | 14 -- ProjectSettings/ProjectSettings.asset | 2 +- 51 files changed, 1011 insertions(+), 391 deletions(-) rename Assets/{Resources/Configs.meta => AddressableAssetsData.meta} (77%) create mode 100644 Assets/AddressableAssetsData/AddressableAssetSettings.asset create mode 100644 Assets/AddressableAssetsData/AddressableAssetSettings.asset.meta create mode 100644 Assets/AddressableAssetsData/Android.meta create mode 100644 Assets/AddressableAssetsData/Android/addressables_content_state.bin create mode 100644 Assets/AddressableAssetsData/Android/addressables_content_state.bin.meta create mode 100644 Assets/AddressableAssetsData/AssetGroupTemplates.meta create mode 100644 Assets/AddressableAssetsData/AssetGroupTemplates/Packed Assets.asset create mode 100644 Assets/AddressableAssetsData/AssetGroupTemplates/Packed Assets.asset.meta create mode 100644 Assets/AddressableAssetsData/AssetGroups.meta create mode 100644 Assets/AddressableAssetsData/AssetGroups/Built In Data.asset create mode 100644 Assets/AddressableAssetsData/AssetGroups/Built In Data.asset.meta create mode 100644 Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset create mode 100644 Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset.meta create mode 100644 Assets/AddressableAssetsData/AssetGroups/Schemas.meta create mode 100644 Assets/AddressableAssetsData/AssetGroups/Schemas/Built In Data_PlayerDataGroupSchema.asset create mode 100644 Assets/AddressableAssetsData/AssetGroups/Schemas/Built In Data_PlayerDataGroupSchema.asset.meta create mode 100644 Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_BundledAssetGroupSchema.asset create mode 100644 Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_BundledAssetGroupSchema.asset.meta create mode 100644 Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_ContentUpdateGroupSchema.asset create mode 100644 Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_ContentUpdateGroupSchema.asset.meta create mode 100644 Assets/AddressableAssetsData/DataBuilders.meta create mode 100644 Assets/AddressableAssetsData/DataBuilders/BuildScriptFastMode.asset create mode 100644 Assets/AddressableAssetsData/DataBuilders/BuildScriptFastMode.asset.meta create mode 100644 Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedMode.asset create mode 100644 Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedMode.asset.meta create mode 100644 Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedPlayMode.asset create mode 100644 Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedPlayMode.asset.meta create mode 100644 Assets/AddressableAssetsData/DataBuilders/BuildScriptVirtualMode.asset create mode 100644 Assets/AddressableAssetsData/DataBuilders/BuildScriptVirtualMode.asset.meta create mode 100644 Assets/AddressableAssetsData/DefaultObject.asset create mode 100644 Assets/AddressableAssetsData/DefaultObject.asset.meta create mode 100644 Assets/AddressableAssetsData/ProfileDataSourceSettings.asset create mode 100644 Assets/AddressableAssetsData/ProfileDataSourceSettings.asset.meta create mode 100644 Assets/AddressableAssetsData/iOS.meta create mode 100644 Assets/AddressableAssetsData/iOS/addressables_content_state.bin create mode 100644 Assets/AddressableAssetsData/iOS/addressables_content_state.bin.meta rename Assets/{Resources/Configs/public_conf_1765185287.txt => Configs/public_conf_1765185287.json} (100%) rename Assets/{Resources/Configs/public_conf_1765185287.txt.meta => Configs/public_conf_1765185287.json.meta} (75%) create mode 100644 Assets/SGModule/ConfigLoader/SGModule/Editor/AddressablesManager.cs create mode 100644 Assets/SGModule/ConfigLoader/SGModule/Editor/AddressablesManager.cs.meta diff --git a/Assets/Resources/Configs.meta b/Assets/AddressableAssetsData.meta similarity index 77% rename from Assets/Resources/Configs.meta rename to Assets/AddressableAssetsData.meta index 61d2f6b..c121055 100644 --- a/Assets/Resources/Configs.meta +++ b/Assets/AddressableAssetsData.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 2286bdb9423d4da48ba3b1bd8765173f +guid: 692a8563bf4ba9749905419c982657c8 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Assets/AddressableAssetsData/AddressableAssetSettings.asset b/Assets/AddressableAssetsData/AddressableAssetSettings.asset new file mode 100644 index 0000000..93c6da7 --- /dev/null +++ b/Assets/AddressableAssetsData/AddressableAssetSettings.asset @@ -0,0 +1,110 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 468a46d0ae32c3544b7d98094e6448a9, type: 3} + m_Name: AddressableAssetSettings + m_EditorClassIdentifier: + m_DefaultGroup: a45d0d25213104f44ad8fe07eb3548d1 + m_currentHash: + serializedVersion: 2 + Hash: 24f7d451677154961ad4235510acee73 + m_OptimizeCatalogSize: 0 + m_BuildRemoteCatalog: 0 + m_BundleLocalCatalog: 0 + m_CatalogRequestsTimeout: 0 + m_DisableCatalogUpdateOnStart: 0 + m_IgnoreUnsupportedFilesInBuild: 0 + m_UniqueBundleIds: 0 + m_NonRecursiveBuilding: 1 + m_CCDEnabled: 0 + m_maxConcurrentWebRequests: 3 + m_ContiguousBundles: 1 + m_StripUnityVersionFromBundleBuild: 0 + m_DisableVisibleSubAssetRepresentations: 0 + m_ShaderBundleNaming: 0 + m_ShaderBundleCustomNaming: + m_MonoScriptBundleNaming: 0 + m_CheckForContentUpdateRestrictionsOption: 0 + m_MonoScriptBundleCustomNaming: + m_RemoteCatalogBuildPath: + m_Id: + m_RemoteCatalogLoadPath: + m_Id: + m_ContentStateBuildPathProfileVariableName: + m_CustomContentStateBuildPath: + m_ContentStateBuildPath: + m_BuildAddressablesWithPlayerBuild: 0 + m_overridePlayerVersion: '[UnityEditor.PlayerSettings.bundleVersion]' + m_GroupAssets: + - {fileID: 11400000, guid: 902fafad9bba93345b7a8d95737094ff, type: 2} + - {fileID: 11400000, guid: 0835c4975fed7d14795ec925b54bca80, type: 2} + m_BuildSettings: + m_CompileScriptsInVirtualMode: 0 + m_CleanupStreamingAssetsAfterBuilds: 1 + m_LogResourceManagerExceptions: 1 + m_BundleBuildPath: Temp/com.unity.addressables/AssetBundles + m_ProfileSettings: + m_Profiles: + - m_InheritedParent: + m_Id: 70f0db63e1b2ccc49a35826b26d42ffa + m_ProfileName: Default + m_Values: + - m_Id: 693c6cc232ba75944b76340184d8d5da + m_Value: '{UnityEngine.AddressableAssets.Addressables.RuntimePath}/[BuildTarget]' + - m_Id: 6c2c4720f61c8134b9b4b2c9776cd752 + m_Value: http://[PrivateIpAddress]:[HostingServicePort] + - m_Id: 6e2463dd44eb1f54cb6bd7d1ed217d78 + m_Value: '[UnityEngine.AddressableAssets.Addressables.BuildPath]/[BuildTarget]' + - m_Id: 79ac92be39ae3b548acfff4d617e9f3d + m_Value: ServerData/[BuildTarget] + - m_Id: c213fc96596f0424b92d9b5da98dc49d + m_Value: '[UnityEditor.EditorUserBuildSettings.activeBuildTarget]' + m_ProfileEntryNames: + - m_Id: 693c6cc232ba75944b76340184d8d5da + m_Name: Local.LoadPath + m_InlineUsage: 0 + - m_Id: 6c2c4720f61c8134b9b4b2c9776cd752 + m_Name: Remote.LoadPath + m_InlineUsage: 0 + - m_Id: 6e2463dd44eb1f54cb6bd7d1ed217d78 + m_Name: Local.BuildPath + m_InlineUsage: 0 + - m_Id: 79ac92be39ae3b548acfff4d617e9f3d + m_Name: Remote.BuildPath + m_InlineUsage: 0 + - m_Id: c213fc96596f0424b92d9b5da98dc49d + m_Name: BuildTarget + m_InlineUsage: 0 + m_ProfileVersion: 1 + m_LabelTable: + m_LabelNames: + - default + - config + m_SchemaTemplates: [] + m_GroupTemplateObjects: + - {fileID: 11400000, guid: e3717cb91779b3c42b0fa261a19e2089, type: 2} + m_InitializationObjects: [] + m_CertificateHandlerType: + m_AssemblyName: + m_ClassName: + m_ActivePlayerDataBuilderIndex: 3 + m_DataBuilders: + - {fileID: 11400000, guid: e3793cbe36022934c8e448ba864e7d23, type: 2} + - {fileID: 11400000, guid: c1b22d2e9c442004aa8ce9415342d39b, type: 2} + - {fileID: 11400000, guid: 09b58a3e361fb894bb05487b13037296, type: 2} + - {fileID: 11400000, guid: 451c87b652b66324b93ed04ca22c9f79, type: 2} + m_ActiveProfileId: 70f0db63e1b2ccc49a35826b26d42ffa + m_HostingServicesManager: + m_HostingServiceInfos: [] + m_Settings: {fileID: 11400000} + m_NextInstanceId: 0 + m_RegisteredServiceTypeRefs: [] + m_PingTimeoutInMilliseconds: 5000 diff --git a/Assets/AddressableAssetsData/AddressableAssetSettings.asset.meta b/Assets/AddressableAssetsData/AddressableAssetSettings.asset.meta new file mode 100644 index 0000000..0fb133c --- /dev/null +++ b/Assets/AddressableAssetsData/AddressableAssetSettings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e60983ba8459aa349988c3ecb65abf31 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/Android.meta b/Assets/AddressableAssetsData/Android.meta new file mode 100644 index 0000000..a491e64 --- /dev/null +++ b/Assets/AddressableAssetsData/Android.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 820198255c53d7944a20b1c68c5aa2c9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/Android/addressables_content_state.bin b/Assets/AddressableAssetsData/Android/addressables_content_state.bin new file mode 100644 index 0000000000000000000000000000000000000000..0f61f5fda4223f4ad75293d1f41af93e989164e8 GIT binary patch literal 1454 zcmbtU&2G~`5VlL=BqUMQ1A=1?94ps$+BlIYQW~|QkkTk^=>Z{Y7(K zc_A*m7UBh9)=o=$A}VWX*5lpz=9@oTwq;qrahct$#s-Sf1yA(C?Ncg2DKcT8+(VjZ zA-7u}K&nLWeb3FG?baY;I+L)^A=8qu?baxpuq1v5i*s=We4l5Gl@0u>9JRn%#qKKw zTDb>V!szOEH4t0_*Jqk&C?i1gnvn&_C4(m9jFwtGCh;8TF`o+cOhPI&42UL7%!Y!{ z5z+HzapNH46yve&l3nVo!)TBL=Ol9`A3vECh3lIZ9#?FQz4HV`**8gaO88n2ydZGf z?w&vOYbIF7L1EP@C@My`?kZH;UElRz*2ZVWfaN#_tF*U1&PoUds8&VMsG%6<815L9 z$YcyBgp(OOx=Re~<5@K(d1;Rl2FJ8SvHJE#p6aIv`_2ARgv)0Mht)P)w%>zhA7@-A zDVVnTy3^-WiiGY^m=f%DCSt;7Qe@W=$vZb9j71>@e-g$W4|-vz9R@+SOTy_i^t?%j z`d-H^$kpn|rEJ98RXPvzmtxc3r*tI6Z9;MA+?;4pi80({p!Dgr#!*xagmcp94N>!Q z8VzJzOQUn7FEYJ_`aI)TK+h%NY6@~Qjm9`R5@J0}(nL3muH|ANFlJN=2k%J=cr$lt z2IxdkxIa8gKEsPNx=?_=j)W{Gq%c&^^Mi}aF&+#}s+QkhA`=Egp6WR)EtaFJF6Y3F z6QD(p+h!oF&8l6kzJ6Sm?kJlUt=YD1cE_Zt^{+bpJp6ux_llpQ*_|eeRyU-y>yt@u w&uhp2Zm$laIKr~@uHWY-8 zh@RJr8~Yij7>{k2>{4ePMuQwUCz&((@X@5GyS{1RamCiyJNHnO159GuDdFGErr&IO zp%-+ffop$!pRKo+$9F~?yPE)ytD@igF{-PSbcjVPxXC-{bqkD!sWAs!)lu?+wWGhk29{5 z6inNE-ARs5b|_2<_Bj(VVKXVR%ZTJ%8xh8$ZW}r@?(|yCb{vEqAT;cTanS7q{csxg zW3M3QZX%De5pPzh+|FH!4S$o)krY=6#ews3l0_B9@F@eOk1sWjp{gOAlSZ$JnwQgP zAY(U;PLaCE^h4C=8NUE}DhXFpkXvaq#;K7I>tT{6x@L4O7XyLuqEa|`M^eC>xl1!V zM}or5;Ysoto}|&40`zqtWHB9up?aJjoSl#HU}#dc{Qex7Fd*_+&tYk?99wlh2X34I zE&AIw!(eSy?P~Sq-LiB|*|eu?+qT&qlcvVM>h$B;gQs|}co5C*)KN5gT}pcane^K} uR<+gdH>Z=H-w%DiNn#&@@=ts}|C6iw|5_#m--kbB{mM@O literal 0 HcmV?d00001 diff --git a/Assets/AddressableAssetsData/iOS/addressables_content_state.bin.meta b/Assets/AddressableAssetsData/iOS/addressables_content_state.bin.meta new file mode 100644 index 0000000..016abc9 --- /dev/null +++ b/Assets/AddressableAssetsData/iOS/addressables_content_state.bin.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 56a8814c396664b048814cc6d477d82d +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Configs.meta b/Assets/Configs.meta index 9241642..61d2f6b 100644 --- a/Assets/Configs.meta +++ b/Assets/Configs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 410e26deedfc5864bb5bd6b9cad1f450 +guid: 2286bdb9423d4da48ba3b1bd8765173f folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Assets/Resources/Configs/public_conf_1765185287.txt b/Assets/Configs/public_conf_1765185287.json similarity index 100% rename from Assets/Resources/Configs/public_conf_1765185287.txt rename to Assets/Configs/public_conf_1765185287.json diff --git a/Assets/Resources/Configs/public_conf_1765185287.txt.meta b/Assets/Configs/public_conf_1765185287.json.meta similarity index 75% rename from Assets/Resources/Configs/public_conf_1765185287.txt.meta rename to Assets/Configs/public_conf_1765185287.json.meta index f214d6b..54bb9d6 100644 --- a/Assets/Resources/Configs/public_conf_1765185287.txt.meta +++ b/Assets/Configs/public_conf_1765185287.json.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: f8c67570025fefa448706dadc37c5988 +guid: 7ba7c6a75110f483683dc4885aee0758 TextScriptImporter: externalObjects: {} userData: diff --git a/Assets/Resources/GameConfig.asset b/Assets/Resources/GameConfig.asset index e2a24cd..5437143 100644 --- a/Assets/Resources/GameConfig.asset +++ b/Assets/Resources/GameConfig.asset @@ -12,5 +12,5 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: c836612725633cc4093d7ac06e7d9ef1, type: 3} m_Name: GameConfig m_EditorClassIdentifier: - packageName: com.tronwingame.redhotroast + packageName: com.crazyballcatgame.frozenarena hardwareAcceleration: 1 diff --git a/Assets/Resources/NetworkConfig.asset b/Assets/Resources/NetworkConfig.asset index 809cfc0..509cfbb 100644 --- a/Assets/Resources/NetworkConfig.asset +++ b/Assets/Resources/NetworkConfig.asset @@ -13,6 +13,6 @@ MonoBehaviour: m_Name: NetworkConfig m_EditorClassIdentifier: showNetworkLog: 1 - debugHost: api.jsoncompare.online + debugHost: sandbox-api.swhitegames.tech releaseHost: frozenarena.top connectionMode: 0 diff --git a/Assets/SGModule/ConfigLoader/SGModule/Editor/AddressablesManager.cs b/Assets/SGModule/ConfigLoader/SGModule/Editor/AddressablesManager.cs new file mode 100644 index 0000000..574f2a0 --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Editor/AddressablesManager.cs @@ -0,0 +1,188 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using SGModule.Common.Helper; +using UnityEditor; +using UnityEditor.PackageManager; +using UnityEditor.PackageManager.Requests; +using PackageInfo = UnityEditor.PackageManager.PackageInfo; +#if USE_ADDRESSABLES +using UnityEditor.AddressableAssets; +#endif + +namespace SGModule.Editor { + [InitializeOnLoad] + public static class AddressablesManager { + private const string AddressablesPackageName = "com.unity.addressables"; + private const string AddressablesSymbol = "USE_ADDRESSABLES"; + private static AddRequest _addRequest; + + // 安装标记,避免重复弹窗 + private static bool _isInstallingAddressables; + + static AddressablesManager() { + EditorApplication.projectChanged += OnProjectChanged; // 监听项目变更 + + CheckAndSetupAddressables(); + } + + private static string DefaultConfigsPath => "Assets/Configs"; // 默认的 Addressables 配置路径 + + private static void CheckAndSetupAddressables() { + if (IsAddressablesInstalled()) { + Log.Info("ConfigLoader", "Addressables 已安装,正在初始化..."); + + AddScriptingDefineSymbol(AddressablesSymbol); + +#if USE_ADDRESSABLES + EnsureAddressablesConfigured(); +#endif + } + else { + RemoveScriptingDefineSymbol(AddressablesSymbol); + if (!_isInstallingAddressables) { + PromptToInstallAddressables(); + } + } + } + + private static bool IsAddressablesInstalled() { + return PackageInfo.GetAllRegisteredPackages().Any(package => package.name == AddressablesPackageName); + } + + private static void PromptToInstallAddressables() { + var install = EditorUtility.DisplayDialog( + "Addressables 未安装", + "当前插件依赖 Addressables 功能,请安装以确保正常使用。\n\n是否立即安装 Addressables?", + "安装", + "取消"); + + if (install) { + InstallAddressables(); + } + else { + Log.Warning("ConfigLoader", "用户取消安装 Addressables,部分功能可能无法正常使用!"); + } + } + + private static void InstallAddressables() { + if (_isInstallingAddressables) { + return; // 防止重复安装 + } + + Log.Info("ConfigLoader", "开始安装 Addressables..."); + + _isInstallingAddressables = true; // 标记正在安装,避免重复弹窗 + _addRequest = Client.Add(AddressablesPackageName); + + EditorApplication.update += MonitorAddRequest; + } + + private static void MonitorAddRequest() { + if (_addRequest == null || !_addRequest.IsCompleted) { + return; + } + + EditorApplication.update -= MonitorAddRequest; + + if (_addRequest.Status == StatusCode.Success) { + Log.Info("ConfigLoader", "Addressables 安装成功!"); + + EditorUtility.DisplayDialog("安装完成", "Addressables 安装成功,请稍候等待 Unity 刷新。", "确定"); + + CheckAndSetupAddressables(); + } + else if (_addRequest.Status >= StatusCode.Failure) { + Log.Error("ConfigLoader", $"安装 Addressables 失败:{_addRequest.Error.message}"); + + EditorUtility.DisplayDialog("安装失败", $"安装 Addressables 失败:{_addRequest.Error.message}", "确定"); + } + + _isInstallingAddressables = false; // 重置标记 + } + + private static void AddScriptingDefineSymbol(string symbol) { + var symbols = new List(PlayerSettings + .GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup).Split(';')); + if (symbols.Contains(symbol)) { + return; + } + + + symbols.Add(symbol); + PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, + string.Join(";", symbols)); + Log.Info("ConfigLoader", $"已添加脚本定义符号: {symbol}"); + } + + private static void RemoveScriptingDefineSymbol(string symbol) { + var symbols = new List(PlayerSettings + .GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup).Split(';')); + if (symbols.Contains(symbol)) { + symbols.Remove(symbol); + PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, + string.Join(";", symbols)); + + Log.Info("ConfigLoader", $"已移除脚本定义符号: {symbol}"); + } + } + + private static void OnProjectChanged() { + Log.Info("ConfigLoader", "检测到项目变更,重新检查 Addressables 状态..."); + + CheckAndSetupAddressables(); + } + +#if USE_ADDRESSABLES + private static void EnsureAddressablesConfigured() { + var settings = AddressableAssetSettingsDefaultObject.Settings; + + if (settings == null) { + Log.Info("ConfigLoader", "正在初始化 Addressables 设置..."); + + settings = AddressableAssetSettingsDefaultObject.GetSettings(true); // 自动创建配置 + } + + // 确保默认的 Configs 文件夹存在并被添加到 Addressables + var needRefresh = false; + if (!Directory.Exists(DefaultConfigsPath)) { + Directory.CreateDirectory(DefaultConfigsPath); + Log.Info("ConfigLoader", $"已创建文件夹: {DefaultConfigsPath}"); + + needRefresh = true; + } + + if (!IsFolderInAddressables(DefaultConfigsPath)) { + var guid = AssetDatabase.AssetPathToGUID(DefaultConfigsPath); + var group = settings.DefaultGroup; + settings.CreateOrMoveEntry(guid, group)?.SetLabel("config", true, true); + needRefresh = true; + } + + if (needRefresh) { + AssetDatabase.Refresh(); + } + } + + private static bool IsFolderInAddressables(string folderPath) { + var settings = AddressableAssetSettingsDefaultObject.Settings; + foreach (var group in settings.groups) + { + if (group) + { + foreach (var entry in group.entries) + { + if (AssetDatabase.GUIDToAssetPath(entry.guid) == folderPath) + { + return true; + } + } + } + } + + + return false; + } +#endif + } +} diff --git a/Assets/SGModule/ConfigLoader/SGModule/Editor/AddressablesManager.cs.meta b/Assets/SGModule/ConfigLoader/SGModule/Editor/AddressablesManager.cs.meta new file mode 100644 index 0000000..784773a --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Editor/AddressablesManager.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 383ac67f695b4c6e94ba988c9303cd5b +timeCreated: 1733734050 \ No newline at end of file diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/ConfigFileManager.cs b/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/ConfigFileManager.cs index 8d130c6..9c8598f 100644 --- a/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/ConfigFileManager.cs +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/ConfigFileManager.cs @@ -3,10 +3,8 @@ using System.IO; using SGModule.Common.Helper; using UnityEngine; -namespace SGModule.ConfigLoader -{ - public class ConfigFileManager - { +namespace SGModule.ConfigLoader { + public class ConfigFileManager { private const int MaxErrorCount = 6; private const string ConfigFileNameKey = "ConfigFileName"; private const string FirstLaunchKey = "FirstLaunch"; @@ -17,59 +15,44 @@ namespace SGModule.ConfigLoader private static bool IsFirstLaunch => !PlayerPrefs.HasKey(FirstLaunchKey); private static string SavedConfigFileName => PlayerPrefs.GetString(ConfigFileNameKey); - private static void SetFirstLaunch() - { + private static void SetFirstLaunch() { PlayerPrefs.SetInt(FirstLaunchKey, 1); } - private static void SetSavedConfigFileName(string name) - { + private static void SetSavedConfigFileName(string name) { PlayerPrefs.SetString(ConfigFileNameKey, name); } - private void IncrementErrorCount() - { + private void IncrementErrorCount() { _initConfigErrorCount++; } // 检查是否需要下载新配置,基于传入的期望配置文件名setting - private static bool HasNewConfig(string expectedSetting) - { - if (string.IsNullOrEmpty(SavedConfigFileName)) - { + private static bool HasNewConfig(string expectedSetting) { + if (string.IsNullOrEmpty(SavedConfigFileName)) { return true; } return !SavedConfigFileName.Equals(expectedSetting); } - private void FirstLaunchCopyConfig(Action callback) - { + private void FirstLaunchCopyConfig(Action callback) { SetFirstLaunch(); - Debug.Log("000000000000000000000000000000"); - FileNetworkManager.Instance.CopyStreamingAssetsToPersistentDataPath(result => - { - Debug.Log("0000000000000000000000000000006"); + + FileNetworkManager.Instance.CopyStreamingAssetsToPersistentDataPath(result => { var isSuccess = false; - if (result) - { - Debug.Log("0000000000000000000000000000007"); + if (result) { var names = FileNetworkManager.Instance.GetFileNamesFromPersistentDataPath(FileNetworkManager.FolderName); - if (names.Length > 0) - { - Debug.Log("0000000000000000000000000000008"); - Debug.Log("0000000000000000000000000000009"+names[0]); + if (names.Length > 0) { SetSavedConfigFileName(names[0]); isSuccess = true; } } - else - { + else { Log.ConfigLoader.Error("拷贝文件失败 请检查Configs文件夹是否有配置文件"); } - if (!isSuccess) - { + if (!isSuccess) { IncrementErrorCount(); } @@ -77,20 +60,16 @@ namespace SGModule.ConfigLoader }); } - private void DownloadConfig(string cdnUrl, string setting, Action callback) - { + private void DownloadConfig(string cdnUrl, string setting, Action callback) { var url = $"{cdnUrl}/config/{setting}"; Log.ConfigLoader.Info($"开始下载配置文件 {url}", false); - FileNetworkManager.Instance.ReadData(url, result => - { - if (!string.IsNullOrEmpty(result)) - { + FileNetworkManager.Instance.ReadData(url, result => { + if (!string.IsNullOrEmpty(result)) { SetSavedConfigFileName(setting); FileNetworkManager.Instance.WriteToPersistentData(FileNetworkManager.Instance.GetConfigFOlderPath(), setting, result); callback?.Invoke(true, result); } - else - { + else { Log.ConfigLoader.Error("下载配置文件失败"); IncrementErrorCount(); callback?.Invoke(false, null); @@ -98,92 +77,40 @@ namespace SGModule.ConfigLoader }); } - private void ReadLocalConfig(Action callback) - { + private void ReadLocalConfig(Action callback) { var savedCfgName = SavedConfigFileName; Log.ConfigLoader.Info($"开始读取本地配置文件 {savedCfgName}", false); - if (string.IsNullOrEmpty(savedCfgName)) - { + if (string.IsNullOrEmpty(savedCfgName)) { IncrementErrorCount(); callback?.Invoke(false, null); return; } var path = Path.Combine(FileNetworkManager.Instance.GetConfigFOlderPath(), savedCfgName); - bool have_config = false; - if (Directory.Exists(FileNetworkManager.Instance.GetConfigFOlderPath())) - { - // 获取该目录下的所有文件 - string[] files = Directory.GetFiles(FileNetworkManager.Instance.GetConfigFOlderPath()); - - if (files.Length > 0) - { - Debug.Log("文件夹下有文件"); - have_config = true; + FileNetworkManager.Instance.ReadData(path, result => { + if (!string.IsNullOrEmpty(result)) { + callback?.Invoke(true, result); } - else - { - Debug.Log("文件夹为空"); + else { + Log.ConfigLoader.Error("读取本地数据异常"); + IncrementErrorCount(); + callback?.Invoke(false, null); } - } - else - { - Debug.Log("文件夹不存在"); - - } - if (have_config) - { - FileNetworkManager.Instance.ReadData(path, result => - { - if (!string.IsNullOrEmpty(result)) - { - callback?.Invoke(true, result); - } - else - { - Log.ConfigLoader.Error("读取本地数据异常"); - IncrementErrorCount(); - callback?.Invoke(false, null); - } - }); - } - else - { - Debug.Log(savedCfgName); - FirstLaunchCopyConfig(success => - { - path = Path.Combine(FileNetworkManager.Instance.GetConfigFOlderPath(), SavedConfigFileName); - FileNetworkManager.Instance.ReadData(path, result => - { - if (!string.IsNullOrEmpty(result)) - { - - callback?.Invoke(true, result); - } - }); - }); - - - } + }); } /// /// 配置文件检查与加载流程 /// - public void CheckAndLoadConfig(ConfigInitOptions initOptions, Action onConfigLoaded, Action callback) - { - if (HasExceededMaxErrors) - { + public void CheckAndLoadConfig(ConfigInitOptions initOptions, Action onConfigLoaded, Action callback) { + if (HasExceededMaxErrors) { callback?.Invoke(ConfigLoaderState.Failed); return; } -Debug.Log("是否第一次登录"+IsFirstLaunch); - if (IsFirstLaunch) - { - FirstLaunchCopyConfig(success => - { - if (!success) - { + + if (IsFirstLaunch) { + FirstLaunchCopyConfig(success => { + if (!success) { IncrementErrorCount(); } @@ -191,25 +118,18 @@ Debug.Log("是否第一次登录"+IsFirstLaunch); }); return; } -Debug.Log("是否需要下载"+HasNewConfig(initOptions.Setting)); - if (HasNewConfig(initOptions.Setting)) - { - DownloadConfig(initOptions.CdnUrl, initOptions.Setting, (success, json) => - { - if (success) - { + + if (HasNewConfig(initOptions.Setting)) { + DownloadConfig(initOptions.CdnUrl, initOptions.Setting, (success, json) => { + if (success) { ReloadConfig(json, onConfigLoaded, callback); } - else - { - ReadLocalConfig((readSuccess, localJson) => - { - if (readSuccess) - { + else { + ReadLocalConfig((readSuccess, localJson) => { + if (readSuccess) { ReloadConfig(localJson, onConfigLoaded, callback); } - else - { + else { callback?.Invoke(ConfigLoaderState.Failed); } }); @@ -218,18 +138,13 @@ Debug.Log("是否需要下载"+HasNewConfig(initOptions.Setting)); return; } - ReadLocalConfig((success, json) => - { - if (success) - { + ReadLocalConfig((success, json) => { + if (success) { ReloadConfig(json, onConfigLoaded, callback); } - else - { - FirstLaunchCopyConfig(result => - { - if (!result) - { + else { + FirstLaunchCopyConfig(result => { + if (!result) { IncrementErrorCount(); } @@ -239,10 +154,8 @@ Debug.Log("是否需要下载"+HasNewConfig(initOptions.Setting)); }); } - private static void ReloadConfig(string json, Action onConfigLoaded, Action callback) - { - if (string.IsNullOrWhiteSpace(json)) - { + private static void ReloadConfig(string json, Action onConfigLoaded, Action callback) { + if (string.IsNullOrWhiteSpace(json)) { callback?.Invoke(ConfigLoaderState.JsonEmptyError); return; } diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/FileNetworkManager.cs b/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/FileNetworkManager.cs index 831cfb2..5d07883 100644 --- a/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/FileNetworkManager.cs +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/FileNetworkManager.cs @@ -6,9 +6,9 @@ using System.Linq; using SGModule.Common.Base; using SGModule.Common.Helper; using UnityEngine; +using UnityEngine.AddressableAssets; using UnityEngine.Networking; -using System.Threading.Tasks; - +using UnityEngine.ResourceManagement.AsyncOperations; #if UNITY_EDITOR using UnityEditor; #endif @@ -16,53 +16,42 @@ using UnityEditor; #if USE_ADDRESSABLES #endif -namespace SGModule.ConfigLoader -{ - public class FileNetworkManager : SingletonMonoBehaviour - { +namespace SGModule.ConfigLoader { + public class FileNetworkManager : SingletonMonoBehaviour { public const string FolderName = "Configs"; private const string FolderLabel = "config"; private string _configFolderPath; - protected override void Awake() - { + protected override void Awake() { base.Awake(); _configFolderPath = Path.Combine(Application.persistentDataPath, FolderName); } - public string GetConfigFOlderPath() - { + public string GetConfigFOlderPath() { return _configFolderPath; } // 示例解析文件列表方法(你可以根据实际需求实现) - private List ParseFileList(string data) - { + private List ParseFileList(string data) { // 假设 data 是文件列表的文本,解析文件名 // 根据实际情况解析,例如通过换行符分割 return data.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).ToList(); } - public void CopyStreamingAssetsToPersistentDataPath(Action onComplete = null) - { - Debug.Log("0000000000000000000000000000001"); + public void CopyStreamingAssetsToPersistentDataPath(Action onComplete = null) { // 如果目标文件夹不存在,创建它 - if (!Directory.Exists(_configFolderPath)) - { + if (!Directory.Exists(_configFolderPath)) { Directory.CreateDirectory(_configFolderPath); } - Debug.Log("0000000000000000000000000000002"); - // CopyFile(onComplete); + StartCoroutine(CopyFile(onComplete)); } - private void HandleInitializationError() - { + private void HandleInitializationError() { // 检查文件是否存在 var path = $"{Application.dataPath}/Library/com.unity.addressables/aa/Android/settings.json"; - if (!File.Exists(path)) - { + if (!File.Exists(path)) { Log.ConfigLoader.Warning( $"Settings file not found at: {path}. Rebuilding Addressables may be required."); } @@ -71,104 +60,68 @@ namespace SGModule.ConfigLoader // 提示用户或执行其他逻辑 // 比如:显示弹窗或退出程序 } - private IEnumerator CopyFile(Action onComplete = null) -{ - Debug.Log("开始加载 Configs 文件夹"); - TextAsset[] files = Resources.LoadAll("Configs"); + private IEnumerator CopyFile(Action onComplete = null) { +#if USE_ADDRESSABLES + var handle = Addressables.LoadResourceLocationsAsync(FolderLabel); - if (files.Length > 0) - { - TextAsset jsonFile = files[0]; - string jsonFileName = jsonFile.name; + yield return handle; - Log.ConfigLoader.Info($"Loaded JSON Name:{jsonFileName} content: " + jsonFile.text); + if (handle.Status == AsyncOperationStatus.Succeeded) { + // 查找以 ".json" 结尾的文件 + var jsonLocation = handle.Result.FirstOrDefault(loc => loc.PrimaryKey.EndsWith(".json")); - if (!Directory.Exists(_configFolderPath)) - Directory.CreateDirectory(_configFolderPath); + if (jsonLocation != null) { + var jsonFileName = Path.GetFileName(jsonLocation.PrimaryKey); + // 加载 JSON 文件 + var textAssetAsync = Addressables.LoadAssetAsync(jsonLocation); - var destFilePath = Path.Combine(_configFolderPath, jsonFileName + ".json"); + yield return textAssetAsync; - // 同步写入文件 - File.WriteAllBytes(destFilePath, jsonFile.bytes); - - // 等待一帧再执行回调,保持协程风格 - yield return null; - onComplete?.Invoke(true); - } - else - { - Log.ConfigLoader.Error("Resources/Configs 下没有找到任何 TextAsset 文件"); - yield return null; - onComplete?.Invoke(false); - } -} - // private IEnumerable CopyFile(Action onComplete = null) - // { + if (textAssetAsync.Status == AsyncOperationStatus.Succeeded) { + var jsonFile = textAssetAsync.Result; + Log.ConfigLoader.Info($"Loaded JSON Name:{jsonFileName} content: " + jsonFile.text); - // // if (handle.Status == AsyncOperationStatus.Succeeded) { - // // 查找以 ".json" 结尾的文件 - // // var jsonLocation = handle.Result.FirstOrDefault(loc => loc.PrimaryKey.EndsWith(".json")); + var destFilePath = Path.Combine(_configFolderPath, jsonFileName); + File.WriteAllBytes(destFilePath, jsonFile.bytes); + onComplete?.Invoke(true); + } + else { + Log.ConfigLoader.Error("Failed to load JSON file"); - // // if (jsonLocation != null) { - // // var jsonFileName = Path.GetFileName(jsonLocation.PrimaryKey); - // // 加载 JSON 文件 - // // var textAssetAsync = Addressables.LoadAssetAsync(jsonLocation); - // Debug.Log("0000000000000000000000000000003"); - // TextAsset[] files = Resources.LoadAll("Configs"); - // // yield return textAssetAsync; + onComplete?.Invoke(false); + } + } + else { + Log.ConfigLoader.Error("No JSON file found in folder"); - // // if (textAssetAsync.Status == AsyncOperationStatus.Succeeded) - // // { - // TextAsset jsonFile = files[0]; - // string jsonFileName = jsonFile.name; - // Log.ConfigLoader.Info($"Loaded JSON Name:{jsonFileName} content: " + jsonFile.text); + onComplete?.Invoke(false); + } + } + else { + Log.ConfigLoader.Error("Failed to load folder resources"); - // Debug.Log("0000000000000000000000000000004"); - // var destFilePath = Path.Combine(_configFolderPath, jsonFileName); - // File.WriteAllBytes(destFilePath, jsonFile.bytes); - // Debug.Log("0000000000000000000000000000005"); - // onComplete?.Invoke(true); + onComplete?.Invoke(false); + } +#else + Log.Error( "没有 Addressables 插件,请检查 "); + yield break; +#endif + } - // // } - // // else { - // // Log.ConfigLoader.Error("Failed to load JSON file"); - - // // onComplete?.Invoke(false); - // // } - // // } - // // else { - // // Log.ConfigLoader.Error("No JSON file found in folder"); - - // // onComplete?.Invoke(false); - // // } - // // } - // // else - // // { - // // Log.ConfigLoader.Error("Failed to load folder resources"); - - // // onComplete?.Invoke(false); - // // } - - // } - - private IEnumerator CopyFile(string sourceFile, string destFile, Action onComplete = null) - { + private IEnumerator CopyFile(string sourceFile, string destFile, Action onComplete = null) { var filePath = "file://" + sourceFile; - using (var www = UnityWebRequest.Get(filePath)) - { + using (var www = UnityWebRequest.Get(filePath)) { yield return www.SendWebRequest(); - if (www.result == UnityWebRequest.Result.Success) - { + if (www.result == UnityWebRequest.Result.Success) { File.WriteAllBytes(destFile, www.downloadHandler.data); Log.ConfigLoader.Info($"File copied to {destFile}"); onComplete?.Invoke(true); } - else - { + else { Log.ConfigLoader.Error("Failed to copy file: " + www.error); onComplete?.Invoke(false); @@ -181,8 +134,7 @@ namespace SGModule.ConfigLoader /// /// /// - public void ReadData(string path, Action callback) - { + public void ReadData(string path, Action callback) { StartCoroutine(ReadDataEnumerator(path, callback)); } @@ -192,17 +144,14 @@ namespace SGModule.ConfigLoader /// /// /// - private IEnumerator ReadDataEnumerator(string path, Action callback) - { + private IEnumerator ReadDataEnumerator(string path, Action callback) { string fullPath; // 判断是网络URL还是本地文件路径 - if (path.StartsWith("http://") || path.StartsWith("https://")) - { + if (path.StartsWith("http://") || path.StartsWith("https://")) { fullPath = path; // 网络URL #if UNITY_EDITOR - if (path.StartsWith("http://") && PlayerSettings.insecureHttpOption == InsecureHttpOption.NotAllowed) - { + if (path.StartsWith("http://") && PlayerSettings.insecureHttpOption == InsecureHttpOption.NotAllowed) { Log.ConfigLoader.Error("发起了 HTTP 链接,但设置了不允许非Https连接,请检查设置!!!"); callback?.Invoke(null); @@ -210,26 +159,22 @@ namespace SGModule.ConfigLoader } #endif } - else - { + else { // 本地文件路径 fullPath = "file://" + path; } -Debug.Log(fullPath); + // 使用UnityWebRequest读取数据 - using (var webRequest = UnityWebRequest.Get(fullPath)) - { + using (var webRequest = UnityWebRequest.Get(fullPath)) { yield return webRequest.SendWebRequest(); if (webRequest.result == UnityWebRequest.Result.ConnectionError || - webRequest.result == UnityWebRequest.Result.ProtocolError) - { + webRequest.result == UnityWebRequest.Result.ProtocolError) { Log.ConfigLoader.Error($"Error while reading file: {webRequest.error} path: {fullPath}"); callback?.Invoke(null); // 返回null表示出错 } - else - { + else { var data = webRequest.downloadHandler.text; callback?.Invoke(data); // 通过回调传出数据 } @@ -242,21 +187,18 @@ Debug.Log(fullPath); /// 文件夹名称 /// 文件名称 /// 要写入的内容 - public void WriteToPersistentData(string folderName, string fileName, string content) - { + public void WriteToPersistentData(string folderName, string fileName, string content) { // 获取持久化数据路径 var folderPath = Path.Combine(Application.persistentDataPath, folderName); // 如果文件夹不存在,则创建它 - if (!Directory.Exists(folderPath)) - { + if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } // 删除原有文件 var existingFiles = Directory.GetFiles(folderPath); - foreach (var file in existingFiles) - { + foreach (var file in existingFiles) { File.Delete(file); } @@ -275,12 +217,11 @@ Debug.Log(fullPath); /// /// /// - public string[] GetFileNamesFromPersistentDataPath(string subdirectory) - { + public string[] GetFileNamesFromPersistentDataPath(string subdirectory) { var directoryPath = Path.Combine(Application.persistentDataPath, subdirectory); if (Directory.Exists(directoryPath)) - // 获取目录中的所有文件名 + // 获取目录中的所有文件名 { return Directory.GetFiles(directoryPath) .Select(Path.GetFileName) // 只提取文件名 diff --git a/Assets/SGModule/Net/SGModule/Scripts/Core/NetChecker.cs b/Assets/SGModule/Net/SGModule/Scripts/Core/NetChecker.cs index 2d77373..1c2eeba 100644 --- a/Assets/SGModule/Net/SGModule/Scripts/Core/NetChecker.cs +++ b/Assets/SGModule/Net/SGModule/Scripts/Core/NetChecker.cs @@ -7,24 +7,20 @@ using SGModule.Common.Helper; using UnityEngine; using UnityEngine.Networking; -namespace SGModule.Net -{ - public enum ConnectionStatus - { +namespace SGModule.Net { + public enum ConnectionStatus { Uninitialized, // 未初始化 Connected, // 已连接 Disconnected // 未连接 } // 网络检测类 - public class NetChecker : SingletonMonoBehaviour - { + public class NetChecker : SingletonMonoBehaviour { private const float WebRequestInterval = 5f; private const float PingInterval = 2; // 可配置多个检测 URL - [SerializeField] - private List checkUrls = new() { + [SerializeField] private List checkUrls = new() { "https://www.baidu.com", // 国内 URL "https://www.google.com" // 国外 URL }; @@ -49,19 +45,16 @@ namespace SGModule.Net /// /// null = 未检测;true = 联网;false = 未联网 /// - private bool? IsConnected - { + private bool? IsConnected { get; set; } - private void OnEnable() - { + private void OnEnable() { StartCheckingInternet(); } - private void OnDisable() - { + private void OnDisable() { StopCheckingInternet(); } @@ -71,84 +64,69 @@ namespace SGModule.Net /// 最多等待的总时间(秒) /// 每次重试间隔 /// 检测结果回调 - public IEnumerator WaitUntilNetworkConnected(float timeout, float checkInterval, Action callback) - { + public IEnumerator WaitUntilNetworkConnected(float timeout, float checkInterval, Action callback) { var elapsed = 0f; // 阶段 1: 等待初始化完成 - while (!IsConnected.HasValue && elapsed < timeout) - { + while (!IsConnected.HasValue && elapsed < timeout) { yield return new WaitForSeconds(checkInterval); elapsed += checkInterval; } - if (!IsConnected.HasValue) - { + if (!IsConnected.HasValue) { Log.Net.Warning("网络检测初始化超时!"); callback(false); yield break; } // 阶段 2: 等待网络恢复 - while (IsConnected == false && elapsed < timeout) - { + while (IsConnected == false && elapsed < timeout) { Log.Net.Warning($"网络异常,等待中... 已耗时: {elapsed:F1}s"); yield return new WaitForSeconds(checkInterval); elapsed += checkInterval; } var success = IsConnected == true; - if (!success) - { + if (!success) { Log.Net.Warning("网络连接等待超时!"); } callback(success); } - public ConnectionStatus GetConnectionStatus() - { - return IsConnected switch - { + public ConnectionStatus GetConnectionStatus() { + return IsConnected switch { null => ConnectionStatus.Uninitialized, true => ConnectionStatus.Connected, false => ConnectionStatus.Disconnected }; } - public void Init() - { + public void Init() { StartCheckingInternet(); } - private void StartCheckingInternet() - { + private void StartCheckingInternet() { _checkInterval = usePingCheck ? PingInterval : WebRequestInterval; _checkInternetCoroutine ??= StartCoroutine(CheckInternetRoutine()); } - private void StopCheckingInternet() - { - if (_checkInternetCoroutine != null) - { + private void StopCheckingInternet() { + if (_checkInternetCoroutine != null) { StopCoroutine(_checkInternetCoroutine); _checkInternetCoroutine = null; } } - private IEnumerator CheckInternetRoutine() - { - while (true) - { - if (_isChecking) - { + private IEnumerator CheckInternetRoutine() { + while (true) { + if (_isChecking) { yield break; // 避免并发冲突 } _isChecking = true; - if (QuickNetDeviceCheck()) - { + if (QuickNetDeviceCheck()) { // if (usePingCheck) { yield return CheckWithPing(); // } @@ -156,13 +134,11 @@ namespace SGModule.Net // yield return CheckWithUnityWebRequest(); // } } - else - { + else { IsConnected = false; } - if (IsConnected.HasValue && _lastConnected != IsConnected.Value) - { + if (IsConnected.HasValue && _lastConnected != IsConnected.Value) { Log.Net.Info($"网络状态变化: {IsConnected}"); _lastConnected = IsConnected.Value; } @@ -175,46 +151,42 @@ namespace SGModule.Net /// /// 使用 Ping 检测网络连通性 /// - private IEnumerator CheckWithPing() - { + private IEnumerator CheckWithPing() { var pings = _pingAddresses.Select(ip => new Ping(ip)).ToList(); var startTime = Time.realtimeSinceStartup; var success = false; - // // 等待所有 Ping 返回结果或超时 - // while (Time.realtimeSinceStartup - startTime < _checkInterval) { - // foreach (var ping in pings) { - // if (ping.isDone && ping.time >= 0) { - // success = true; - // break; - // } - // } + // 等待所有 Ping 返回结果或超时 + while (Time.realtimeSinceStartup - startTime < _checkInterval) { + foreach (var ping in pings) { + if (ping.isDone && ping.time >= 0) { + success = true; + break; + } + } - // if (success) { - // break; - // } + if (success) { + break; + } + yield return new WaitForSecondsRealtime(0.1f); + } - // } - yield return new WaitForSecondsRealtime(0.1f); // 如果有任意一个 Ping 成功,网络即为可用 - IsConnected = true; + IsConnected = success; } /// /// 使用 UnityWebRequest 检测网络连通性 /// - private IEnumerator CheckWithUnityWebRequest() - { - if (!string.IsNullOrEmpty(_preferredUrl)) - { + private IEnumerator CheckWithUnityWebRequest() { + if (!string.IsNullOrEmpty(_preferredUrl)) { var request = UnityWebRequest.Get(_preferredUrl); - request.timeout = (int)_checkInterval; + request.timeout = (int) _checkInterval; yield return request.SendWebRequest(); - if (request.result == UnityWebRequest.Result.Success) - { + if (request.result == UnityWebRequest.Result.Success) { IsConnected = true; request.Dispose(); yield break; @@ -230,30 +202,25 @@ namespace SGModule.Net var ops = new List(); var requests = new List(); - foreach (var url in checkUrls) - { + foreach (var url in checkUrls) { var req = UnityWebRequest.Get(url); - req.timeout = (int)_checkInterval; + req.timeout = (int) _checkInterval; ops.Add(req.SendWebRequest()); requests.Add(req); } yield return StartCoroutine(WaitForAnyRequest(ops)); - foreach (var req in requests) - { + foreach (var req in requests) { req.Dispose(); } } // 等待任意一个请求完成并返回 - private IEnumerator WaitForAnyRequest(List ops) - { - while (ops.Any(op => !op.isDone)) - { - if (ops.Any(op => op.isDone && op.webRequest.result == UnityWebRequest.Result.Success)) - { + private IEnumerator WaitForAnyRequest(List ops) { + while (ops.Any(op => !op.isDone)) { + if (ops.Any(op => op.isDone && op.webRequest.result == UnityWebRequest.Result.Success)) { break; } @@ -262,10 +229,8 @@ namespace SGModule.Net var successOp = ops.FirstOrDefault(op => op.webRequest.result == UnityWebRequest.Result.Success); - if (successOp == null) - { - foreach (var op in ops.Where(op => op.isDone)) - { + if (successOp == null) { + foreach (var op in ops.Where(op => op.isDone)) { Log.Net.Warning($"请求失败: {op.webRequest.url}, 错误: {op.webRequest.error}"); } } @@ -275,41 +240,32 @@ namespace SGModule.Net } // 添加或删除检查 URL - public void AddCheckUrl(string url) - { - if (!checkUrls.Contains(url)) - { + public void AddCheckUrl(string url) { + if (!checkUrls.Contains(url)) { checkUrls.Add(url); } } - public void RemoveCheckUrl(string url) - { - if (checkUrls.Contains(url)) - { + public void RemoveCheckUrl(string url) { + if (checkUrls.Contains(url)) { checkUrls.Remove(url); } } - public void AddPingTarget(string ip) - { - if (!_pingAddresses.Contains(ip)) - { + public void AddPingTarget(string ip) { + if (!_pingAddresses.Contains(ip)) { _pingAddresses.Add(ip); } } - public void RemovePingTarget(string ip) - { - if (_pingAddresses.Contains(ip)) - { + public void RemovePingTarget(string ip) { + if (_pingAddresses.Contains(ip)) { _pingAddresses.Remove(ip); } } // 切换是否使用 Ping 检测 - public void SetUsePingCheck(bool enablePing) - { + public void SetUsePingCheck(bool enablePing) { usePingCheck = enablePing; #if UNITY_WEBGL usePingCheck = false; @@ -317,10 +273,8 @@ usePingCheck = false; _checkInterval = usePingCheck ? PingInterval : WebRequestInterval; } - private bool QuickNetDeviceCheck() - { - if (Application.isEditor) - { + private bool QuickNetDeviceCheck() { + if (Application.isEditor) { return true; } diff --git a/Packages/manifest.json b/Packages/manifest.json index 60e992f..5d184bb 100644 --- a/Packages/manifest.json +++ b/Packages/manifest.json @@ -1,6 +1,7 @@ { "dependencies": { "com.unity.2d.sprite": "1.0.0", + "com.unity.addressables": "1.22.3", "com.unity.collab-proxy": "2.7.1", "com.unity.feature.development": "1.0.1", "com.unity.nuget.newtonsoft-json": "3.2.1", diff --git a/Packages/packages-lock.json b/Packages/packages-lock.json index 0453efe..bff37a0 100644 --- a/Packages/packages-lock.json +++ b/Packages/packages-lock.json @@ -6,6 +6,20 @@ "source": "builtin", "dependencies": {} }, + "com.unity.addressables": { + "version": "1.22.3", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.modules.assetbundle": "1.0.0", + "com.unity.modules.jsonserialize": "1.0.0", + "com.unity.modules.imageconversion": "1.0.0", + "com.unity.modules.unitywebrequest": "1.0.0", + "com.unity.scriptablebuildpipeline": "1.21.25", + "com.unity.modules.unitywebrequestassetbundle": "1.0.0" + }, + "url": "https://packages.unity.com" + }, "com.unity.collab-proxy": { "version": "2.7.1", "depth": 0, @@ -93,6 +107,13 @@ }, "url": "https://packages.unity.com" }, + "com.unity.scriptablebuildpipeline": { + "version": "1.21.25", + "depth": 1, + "source": "registry", + "dependencies": {}, + "url": "https://packages.unity.com" + }, "com.unity.services.core": { "version": "1.14.0", "depth": 1, diff --git a/ProjectSettings/GvhProjectSettings.xml b/ProjectSettings/GvhProjectSettings.xml index cf5bf78..88f2c37 100644 --- a/ProjectSettings/GvhProjectSettings.xml +++ b/ProjectSettings/GvhProjectSettings.xml @@ -1,19 +1,5 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/ProjectSettings/ProjectSettings.asset b/ProjectSettings/ProjectSettings.asset index 07ed250..75e30d3 100644 --- a/ProjectSettings/ProjectSettings.asset +++ b/ProjectSettings/ProjectSettings.asset @@ -898,7 +898,7 @@ PlayerSettings: WebGL: UNITY_VISUAL_SCRIPTING;ES3_TMPRO;ES3_UGUI Windows Store Apps: UNITY_VISUAL_SCRIPTING;ES3_TMPRO;ES3_UGUI XboxOne: UNITY_VISUAL_SCRIPTING;ES3_TMPRO;ES3_UGUI - iPhone: MAX;GAME_RELEASE1;UNITY_VISUAL_SCRIPTING;ES3_TMPRO;ES3_UGUI;UNITY_IAP;UNITY_PURCHASING + iPhone: MAX;GAME_RELEASE1;UNITY_VISUAL_SCRIPTING;ES3_TMPRO;ES3_UGUI;USE_ADDRESSABLES;UNITY_IAP;UNITY_PURCHASING tvOS: UNITY_VISUAL_SCRIPTING;ES3_TMPRO;ES3_UGUI additionalCompilerArguments: {} platformArchitecture: {}