using System; using System.Collections.Generic; using UnityEditor; using UnityEditorInternal; using UnityEngine; public sealed class AppSettingsWindow : EditorWindow { private AppSettings settings; private SerializedObject facebook; private int appIndex; private string appName, appId, clientToken; private string appAddress, appChannel, privacyUrl, downloadUrl, gameSceneName; private AssemblyDefinitionAsset hotPatchAssembly; private string addressError; private Vector2 scrollPosition; private bool showTestUrlHelp = false; private bool showUsageHelp = true; private bool showS3Settings; [NonSerialized] private string s3Bucket, s3Region, s3AccessKey, s3SecretKey, s3SessionToken; private const string TestUrlExample = @"TestUserID https://example.com/test/"; [MenuItem("AppSettings/Open Settings")] public static void Open() { var window = GetWindow("AppSettings"); window.minSize = new Vector2(560, 420); window.LoadSettings(); window.Show(); } private void OnEnable() { showUsageHelp = true; LoadSettings(); } private void LoadSettings() { settings = AppHelpProjectSettings.LoadOrCreateAppSettings(); addressError = null; try { appAddress = string.IsNullOrEmpty(settings.AppAddress) ? string.Empty : ClientCrypto.DecryptString(settings.AppAddress); } catch (Exception) { appAddress = string.Empty; addressError = "Failed to decrypt AppAddress. Enter the plain-text address again and save."; } appChannel = settings.AppChannel; privacyUrl = settings.PrivacyUrl; downloadUrl = settings.DownloadUrl; gameSceneName = settings.GameSceneName; hotPatchAssembly = HotPatchAssemblySelection.Find(settings.HotPatchAssemblyName); var facebookAsset = AppHelpProjectSettings.LoadOrCreateFacebookSettings(); facebook = facebookAsset != null ? new SerializedObject(facebookAsset) : null; appName = appId = clientToken = string.Empty; if (facebook == null) return; facebook.Update(); appIndex = Mathf.Max(0, facebook.FindProperty("selectedAppIndex").intValue); appName = ReadFacebookValue("appLabels"); appId = ReadFacebookValue("appIds"); clientToken = ReadFacebookValue("clientTokens"); } private string ReadFacebookValue(string name) { var property = facebook.FindProperty(name); return appIndex < property.arraySize ? property.GetArrayElementAtIndex(appIndex).stringValue : string.Empty; } private void WriteFacebookValue(string name, string value) { var property = facebook.FindProperty(name); while (property.arraySize <= appIndex) { var index = property.arraySize; property.arraySize++; property.GetArrayElementAtIndex(index).stringValue = string.Empty; } property.GetArrayElementAtIndex(appIndex).stringValue = value; } private void OnGUI() { using (new FontSizeScope(2)) DrawWindow(); } private void DrawWindow() { scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition); DrawHybridCLRSetup(); EditorGUILayout.LabelField("Facebook", EditorStyles.boldLabel); if (facebook == null) EditorGUILayout.HelpBox("FacebookSettings.asset was not found in Resources.", MessageType.Error); using (new EditorGUI.DisabledScope(facebook == null)) { appName = EditorGUILayout.TextField("Facebook AppName", appName); appId = EditorGUILayout.TextField("Facebook AppID", appId); clientToken = EditorGUILayout.TextField("Client Token", clientToken); } EditorGUILayout.Space(); EditorGUILayout.LabelField("App", EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); appAddress = EditorGUILayout.TextField(new GUIContent("AppAddress", "Enter a plain-text address. It is encrypted when saved."), appAddress); if (EditorGUI.EndChangeCheck()) addressError = null; if (!string.IsNullOrEmpty(addressError)) EditorGUILayout.HelpBox(addressError, MessageType.Error); appChannel = EditorGUILayout.TextField("AppChannel", appChannel); privacyUrl = EditorGUILayout.TextField("PrivacyUrl", privacyUrl); downloadUrl = EditorGUILayout.TextField(new GUIContent("Hot Patch DownloadUrl", "HTTP(S) resource directory or full manifest.json URL. Use 资源构建/一键打包资源 to export the DLL and manifest."), downloadUrl); hotPatchAssembly = (AssemblyDefinitionAsset)EditorGUILayout.ObjectField( new GUIContent("Hot Patch Assembly", "Select the game runtime asmdef. Save synchronizes the HybridCLR hot-update assembly settings."), hotPatchAssembly, typeof(AssemblyDefinitionAsset), false); EditorGUILayout.LabelField("Saved Assembly", settings.HotPatchAssemblyName); gameSceneName = EditorGUILayout.TextField(new GUIContent("Game Scene Name", "Enter a unique scene name without .unity. It is used to build the scene bundle, which Launch opens at runtime."), gameSceneName); EditorGUILayout.Space(); using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button("Reload")) LoadSettings(); if (GUILayout.Button("Save")) SaveSettings(); using (new EditorGUI.DisabledScope(S3UploadController.IsUploading)) if (GUILayout.Button("一键打包资源")) EditorApplication.ExecuteMenuItem("资源构建/一键打包资源"); } using (new EditorGUI.DisabledScope(S3UploadController.IsUploading || HotPatchResourceActions.IsBuilding || EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer)) { var latest = HotPatchResourceActions.LatestDirectory; using (new EditorGUI.DisabledScope(string.IsNullOrEmpty(latest))) { using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button("使用本地资源测试")) ApplyResourceMode(true); if (GUILayout.Button("恢复正式资源")) ApplyResourceMode(false); } if (GUILayout.Button("上传资源")) S3UploadController.ChooseAndUpload(downloadUrl); } EditorGUILayout.LabelField("启动资源模式", settings.UseLocalHotPatchResources ? "本地资源测试(跳过远程热更新)" : "正式资源(检查远程更新)"); if (string.IsNullOrEmpty(latest)) EditorGUILayout.HelpBox("没有当前平台、程序集和场景对应的完整打包资源,请先 Save,再执行一键打包资源。", MessageType.Info); else EditorGUILayout.LabelField("最近打包资源", System.IO.Path.GetFileName(latest)); try { EditorGUILayout.LabelField("上传目标", "s3://" + S3UploadSettings.Bucket + "/" + S3ResourceUploader.TargetPrefix(downloadUrl) + "/"); } catch (ArgumentException) { EditorGUILayout.LabelField("上传目标", "请设置包含目录的 DownloadUrl"); } DrawS3Settings(); } DrawUsageHelp(); EditorGUILayout.EndScrollView(); } private void ApplyResourceMode(bool localTesting) { try { HotPatchResourceActions.ApplyResources(localTesting); ShowNotification(new GUIContent(localTesting ? "已切换为本地资源测试" : "已恢复正式资源")); } catch (Exception exception) { Debug.LogException(exception); EditorUtility.DisplayDialog("切换资源失败", exception.Message, "确定"); } } private void DrawHybridCLRSetup() { if (HybridCLRPackageSetup.IsInstalled) return; var installing = HybridCLRPackageSetup.IsInstalling; var message = installing ? "Installing the HybridCLR package. Wait for installation and compilation to finish." : "The HybridCLR package is required. Retry installation or add the following Git URL in Package Manager:\n" + HybridCLRPackageSetup.PackageUrl; if (!string.IsNullOrEmpty(HybridCLRPackageSetup.LastError)) message += "\n" + HybridCLRPackageSetup.LastError; EditorGUILayout.HelpBox(message, installing ? MessageType.Info : MessageType.Warning); using (new EditorGUI.DisabledScope(installing || EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer)) if (GUILayout.Button("Retry HybridCLR Installation")) HybridCLRPackageSetup.RetryInstallation(); if (installing) Repaint(); } private void DrawS3Settings() { showS3Settings = EditorGUILayout.Foldout(showS3Settings, "S3 上传配置(仅本机)", true); if (!showS3Settings) return; if (s3Bucket == null) { s3Bucket = S3UploadSettings.Bucket; s3Region = S3UploadSettings.Region; var credentials = S3UploadSettings.LoadCredentials(); s3AccessKey = credentials.AccessKey ?? ""; s3SecretKey = credentials.SecretKey ?? ""; s3SessionToken = credentials.SessionToken ?? ""; } s3Bucket = EditorGUILayout.TextField("Bucket", s3Bucket); s3Region = EditorGUILayout.TextField("Region", s3Region); s3AccessKey = EditorGUILayout.TextField("Access Key", s3AccessKey); s3SecretKey = EditorGUILayout.PasswordField("Secret Key", s3SecretKey); s3SessionToken = EditorGUILayout.PasswordField("Session Token (optional)", s3SessionToken); EditorGUILayout.HelpBox("凭据保存在本机 ~/.aws/credentials 的 app-runtimes 配置中,不进入项目或安装包。上传使用当前 DownloadUrl 的最后一级目录。", MessageType.Info); if (GUILayout.Button("保存 S3 配置")) { try { S3UploadSettings.Save(s3Bucket, s3Region, new S3UploadCredentials { AccessKey = s3AccessKey, SecretKey = s3SecretKey, SessionToken = s3SessionToken }); ShowNotification(new GUIContent("S3 配置已保存到本机")); } catch (Exception exception) { ShowNotification(new GUIContent(exception.Message)); } } } private sealed class FontSizeScope : IDisposable { private readonly Dictionary originalSizes = new Dictionary(); internal FontSizeScope(int increase) { var styles = new[] { EditorStyles.label, EditorStyles.boldLabel, EditorStyles.textField, EditorStyles.foldout, EditorStyles.helpBox, EditorStyles.textArea, GUI.skin.button }; foreach (var style in styles) { if (originalSizes.ContainsKey(style)) continue; originalSizes.Add(style, style.fontSize); var defaultSize = style.font != null && style.font.fontSize > 0 ? style.font.fontSize : 12; style.fontSize = (style.fontSize > 0 ? style.fontSize : defaultSize) + increase; } } public void Dispose() { foreach (var entry in originalSizes) entry.Key.fontSize = entry.Value; } } private void DrawUsageHelp() { EditorGUILayout.Space(12); showTestUrlHelp = EditorGUILayout.Foldout(showTestUrlHelp, "Test URL Setup (iOS)", true); if (showTestUrlHelp) { EditorGUILayout.HelpBox( "After exporting the iOS project, add TestUserID under the main App Target > Info in Xcode. Set its type to String and" + " its value to the complete test URL (for example, https://example.com/test/).\n" + "Alternatively, add the following entries directly inside the root in Info.plist.", MessageType.Info); DrawExample(TestUrlExample, "Copy Info.plist Example"); EditorGUILayout.HelpBox( "iOS reads TestUserID at startup and uses the test URL if it is not empty. Rebuild and launch the app after changing it.\n" + "Remove the key or clear its value to restore the normal flow. TestUrl is always empty on Android and in the Unity Editor.", MessageType.None); } EditorGUILayout.Space(8); showUsageHelp = EditorGUILayout.Foldout(showUsageHelp, "使用注意事项", true); if (showUsageHelp) { EditorGUILayout.HelpBox( "1. 订阅 AppRuntimesEvents.OnPlatformOpen 事件,在回调中停止播放单机游戏的背景音乐。打开 WebView 时会触发该事件。\n\n" + "2. 操作步骤:Save >>> 一键打包资源 >>> 上传资源", MessageType.Info); } } private void DrawExample(string example, string copyLabel) { var style = new GUIStyle(EditorStyles.textArea) { wordWrap = true }; var height = style.CalcHeight(new GUIContent(example), Mathf.Max(200, position.width - 40)); EditorGUILayout.SelectableLabel(example, style, GUILayout.Height(height)); if (!string.IsNullOrEmpty(copyLabel) && GUILayout.Button(copyLabel)) { EditorGUIUtility.systemCopyBuffer = example; ShowNotification(new GUIContent("Example copied")); } } private void SaveSettings() { if (string.IsNullOrWhiteSpace(gameSceneName)) { ShowNotification(new GUIContent("Enter a game scene name")); return; } if (!string.IsNullOrWhiteSpace(downloadUrl) && (!Uri.TryCreate(downloadUrl.Trim(), UriKind.Absolute, out var uri) || (uri.Scheme != "https" && uri.Scheme != "http"))) { ShowNotification(new GUIContent("The hot patch URL must be an absolute HTTP(S) URL")); return; } if (!string.IsNullOrEmpty(addressError)) return; string encryptedAddress; try { encryptedAddress = string.IsNullOrEmpty(appAddress) ? string.Empty : ClientCrypto.EncryptString(appAddress); } catch (Exception) { addressError = "Failed to encrypt AppAddress. Settings were not saved. Enter the address again and retry."; return; } try { HotPatchAssemblySelection.Save(settings, hotPatchAssembly); } catch (Exception exception) { ShowNotification(new GUIContent(exception.Message)); Debug.LogError("[HotPatch] Settings were not saved: " + exception.Message); return; } Undo.RecordObject(settings, "Save AppSettings"); settings.AppAddress = encryptedAddress; settings.AppChannel = appChannel; settings.PrivacyUrl = privacyUrl; settings.DownloadUrl = (downloadUrl ?? string.Empty).Trim(); settings.GameSceneName = gameSceneName.Trim(); EditorUtility.SetDirty(settings); if (facebook != null) { facebook.Update(); WriteFacebookValue("appLabels", appName); WriteFacebookValue("appIds", appId); WriteFacebookValue("clientTokens", clientToken); facebook.ApplyModifiedProperties(); EditorUtility.SetDirty(facebook.targetObject); } AssetDatabase.SaveAssets(); ShowNotification(new GUIContent("Settings saved")); } }