public void QuitGame() { EditorApplication.Exit(0); }
public static void CompressMainLibProjToAAR() { try { string scriptBaseFilename = "aarMainLibProj.py"; string[] pythonScripts = Directory.GetFiles(Path.Combine(Application.dataPath, PsdkUtils.PsdkRootPath), scriptBaseFilename, SearchOption.AllDirectories); if (pythonScripts.Length == 0) { UnityEngine.Debug.LogError("didn't find pythin script " + scriptBaseFilename + " for creating GPGS MainLibProj AAR !"); return; } string pythonScriptFullPath = pythonScripts[0]; DirectoryInfo psdkRootDirInfo = new DirectoryInfo(Path.Combine(Application.dataPath, PsdkUtils.PsdkRootPath)); DirectoryInfo[] MainProjLibs = psdkRootDirInfo.GetDirectories("*", SearchOption.AllDirectories); UnityEngine.Debug.Log(MainProjLibs.Length); foreach (DirectoryInfo directorySelected in MainProjLibs) { if (!directorySelected.ToString().EndsWith("MainLibProj")) { continue; } Process myCustomProcess = new Process(); myCustomProcess.StartInfo.FileName = "python"; myCustomProcess.StartInfo.WorkingDirectory = directorySelected.ToString(); myCustomProcess.StartInfo.Arguments = string.Format("\"{0}\"", pythonScriptFullPath); UnityEngine.Debug.Log(myCustomProcess.StartInfo.FileName + " " + myCustomProcess.StartInfo.Arguments); myCustomProcess.StartInfo.UseShellExecute = false; myCustomProcess.StartInfo.RedirectStandardOutput = true; myCustomProcess.StartInfo.RedirectStandardError = true; myCustomProcess.Start(); myCustomProcess.WaitForExit(); string strOutput = myCustomProcess.StandardOutput.ReadToEnd(); string strErrorOutput = myCustomProcess.StandardError.ReadToEnd(); int rc = myCustomProcess.ExitCode; myCustomProcess.Close(); if (rc != 0) // failed { UnityEngine.Debug.LogError("Failed in " + scriptBaseFilename + ", rc:" + rc); UnityEngine.Debug.LogError(strErrorOutput); UnityEngine.Debug.Log(strOutput); if (UnityEditorInternal.InternalEditorUtility.inBatchMode) { EditorApplication.Exit(rc); } throw new System.Exception("Failed in exceuting " + scriptBaseFilename + " , rc:" + rc); } else { if (strErrorOutput.Length > 0) { UnityEngine.Debug.Log(strErrorOutput); } if (strOutput.Length > 0) { UnityEngine.Debug.Log(strOutput); } } } } catch (System.Exception e) { UnityEngine.Debug.LogException(e); } }
public void OnError(string message) { EditorApplication.Exit((int)Executer.ReturnCodes.RunError); }
public void Build(string overrideExportFolder = null, bool crashWithCodeOnFail = false, bool openFileWindowWhenDone = true) { crashWithCodeIfBuildFails = crashWithCodeOnFail; string exportFolder; if (overrideExportFolder != null) { exportFolder = overrideExportFolder; } else if (useLocalBuildFolderPath) { exportFolder = Path.Combine(Application.dataPath, localBuildFolderPath); if (!Directory.Exists(exportFolder)) { try { // Simplify any ".." relative-ness. var info = Directory.CreateDirectory(exportFolder); exportFolder = new DirectoryInfo(exportFolder).FullName; } catch (Exception) { UnityEngine.Debug.Log("Could not build " + DefinitionName + " because " + "localBuildFolderPath was used and directory " + exportFolder + " could not be created."); } } else { // Simplify any ".." relative-ness. exportFolder = new DirectoryInfo(exportFolder).FullName; } } else if (!TryGetPackageExportFolder(out exportFolder, promptIfNotDefined: true)) { UnityEngine.Debug.LogError("Could not build " + DefinitionName + " because no export folder was chosen."); if (crashWithCodeOnFail) { EditorApplication.Exit((int)ExitCode.NoExportFolderSpecified); } return; } if (_trySuffixWithGitHash) { string hash; if (tryGetGitCommitHash(out hash)) { exportFolder = Path.Combine(exportFolder, DefinitionName + "_" + hash); } else { UnityEngine.Debug.LogWarning("Failed to get git hash."); } } var fullBuildPath = Path.Combine(exportFolder, DefinitionName); string fullExecutablePath = Path.Combine( fullBuildPath, DefinitionName ); var buildOptions = new BuildPlayerOptions() { scenes = _scenes.Where(s => s != null). Select(s => AssetDatabase.GetAssetPath(s)). ToArray(), options = _options, }; foreach (var target in _targets) { buildOptions.target = target; buildOptions.locationPathName = fullExecutablePath + getFileSuffix(target); if (_useSpecificPlayerSettings) { var origFullscreenMode = PlayerSettings.fullScreenMode; var origDefaultWidth = PlayerSettings.defaultScreenWidth; var origDefaultHeight = PlayerSettings.defaultScreenHeight; var origResizableWindow = PlayerSettings.resizableWindow; #if !UNITY_2019_1_OR_NEWER var origResDialogSetting = PlayerSettings.displayResolutionDialog; #endif try { PlayerSettings.fullScreenMode = _playerSettings.fullScreenMode; PlayerSettings.defaultScreenWidth = _playerSettings.defaultScreenWidth; PlayerSettings.defaultScreenHeight = _playerSettings.defaultScreenHeight; PlayerSettings.resizableWindow = _playerSettings.resizableWindow; #if !UNITY_2019_1_OR_NEWER PlayerSettings.displayResolutionDialog = _playerSettings.resolutionDialogSetting; #endif callPreBuildExtensions(fullBuildPath, crashWithCodeOnFail); BuildPipeline.BuildPlayer(buildOptions); callPostBuildExtensions(fullBuildPath, crashWithCodeOnFail); } finally { PlayerSettings.fullScreenMode = origFullscreenMode; PlayerSettings.defaultScreenWidth = origDefaultWidth; PlayerSettings.defaultScreenHeight = origDefaultHeight; PlayerSettings.resizableWindow = origResizableWindow; #if !UNITY_2019_1_OR_NEWER PlayerSettings.displayResolutionDialog = origResDialogSetting; #endif } } else { callPreBuildExtensions(fullBuildPath, crashWithCodeOnFail); BuildPipeline.BuildPlayer(buildOptions); callPostBuildExtensions(fullBuildPath, crashWithCodeOnFail); } if (_options.HasFlag(BuildOptions.EnableHeadlessMode)) { // The -batchmode flag is the only important part of headless mode // for Windows. The EnableHeadlessMode build option only actually has // an effect on Linux standalone builds. // Here, it's being used to mark the _intention_ of a headless build // for Windows builds. var text = "\"" + _definitionName + ".exe" + "\" -batchmode"; var headlessModeBatPath = Path.Combine(Path.Combine(exportFolder, _definitionName), "Run Headless Mode.bat"); File.WriteAllText(headlessModeBatPath, text); } } if (openFileWindowWhenDone) { Process.Start(exportFolder); } }
public static void BuildAndRunInPlayer(PlatformRunnerConfiguration configuration) { NetworkResultsReceiver.StopReceiver(); var settings = new PlayerSettingConfigurator(false); if (configuration.sendResultsOverNetwork) { try { var l = new TcpListener(IPAddress.Any, configuration.port); l.Start(); configuration.port = ((IPEndPoint)l.Server.LocalEndPoint).Port; l.Stop(); } catch (SocketException e) { Debug.LogException(e); if (InternalEditorUtility.inBatchMode) { EditorApplication.Exit(Batch.returnCodeRunError); } } } if (InternalEditorUtility.inBatchMode) { settings.AddConfigurationFile(TestRunnerConfigurator.batchRunFileMarker, ""); } if (configuration.sendResultsOverNetwork) { settings.AddConfigurationFile(TestRunnerConfigurator.integrationTestsNetwork, string.Join("\n", configuration.GetConnectionIPs())); } settings.AddConfigurationFile(TestRunnerConfigurator.testScenesToRun, string.Join("\n", configuration.testScenes.ToArray())); settings.ChangeSettingsForIntegrationTests(); AssetDatabase.Refresh(); var result = BuildPipeline.BuildPlayer(configuration.testScenes.Concat(configuration.buildScenes).ToArray(), configuration.GetTempPath(), configuration.buildTarget, BuildOptions.AutoRunPlayer | BuildOptions.Development); settings.RevertSettingsChanges(); settings.RemoveAllConfigurationFiles(); AssetDatabase.Refresh(); if (!string.IsNullOrEmpty(result)) { if (InternalEditorUtility.inBatchMode) { EditorApplication.Exit(Batch.returnCodeRunError); } return; } if (configuration.sendResultsOverNetwork) { NetworkResultsReceiver.StartReceiver(configuration); } else if (InternalEditorUtility.inBatchMode) { EditorApplication.Exit(Batch.returnCodeTestsOk); } }
static void AndroidBuildFromCommandLine() { try { string versionNumber = DateTime.Now.ToString("yyMMddHHss"); PlayerSettings.companyName = "Altom"; PlayerSettings.productName = "sampleGame"; PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, "fi.altom.altunitytester"); PlayerSettings.bundleVersion = versionNumber; PlayerSettings.Android.bundleVersionCode = int.Parse(versionNumber); PlayerSettings.Android.minSdkVersion = AndroidSdkVersions.AndroidApiLevel23; #if UNITY_2018_1_OR_NEWER PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARMv7; #endif Debug.Log("Starting Android build..." + PlayerSettings.productName + " : " + PlayerSettings.bundleVersion); BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions(); buildPlayerOptions.scenes = new string[] { "Assets/AltUnityTester-BindingsAndExamples(can_be_deleted)/Scenes/Scene 1 AltUnityDriverTestScene.unity", "Assets/AltUnityTester-BindingsAndExamples(can_be_deleted)/Scenes/Scene 2 Draggable Panel.unity", "Assets/AltUnityTester-BindingsAndExamples(can_be_deleted)/Scenes/Scene 3 Drag And Drop.unity", "Assets/AltUnityTester-BindingsAndExamples(can_be_deleted)/Scenes/Scene 4 No Cameras.unity" }; buildPlayerOptions.locationPathName = "sampleGame.apk"; buildPlayerOptions.target = BuildTarget.Android; buildPlayerOptions.options = BuildOptions.Development | BuildOptions.AutoRunPlayer; AltUnityBuilder.AddAltUnityTesterInScritpingDefineSymbolsGroup(BuildTargetGroup.Android); AltUnityBuilder.InsertAltUnityInScene(buildPlayerOptions.scenes[0]); var results = BuildPipeline.BuildPlayer(buildPlayerOptions); AltUnityBuilder.RemoveAltUnityTesterFromScriptingDefineSymbols(BuildTargetGroup.Android); #if UNITY_2017 if (results.Equals("")) { Debug.Log("No Build Errors"); } else { Debug.LogError("Build Error!"); } EditorApplication.Exit(1); #else if (results.summary.totalErrors == 0) { Debug.Log("No Build Errors"); } else { Debug.LogError("Build Error! " + results.steps + "\n Result: " + results.summary.result + "\n Stripping info: " + results.strippingInfo); EditorApplication.Exit(1); } #endif Debug.Log("Finished. " + PlayerSettings.productName + " : " + PlayerSettings.bundleVersion); // EditorApplication.Exit(0); } catch (Exception exception) { Debug.LogException(exception); // EditorApplication.Exit(1); } }
/// <summary>Restart Unity.</summary> /// <param name="executeMethod">Executed method after the restart (optional)</param> public static void RestartUnity(string executeMethod = "") { UnityEditor.SceneManagement.EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); bool success = false; string scriptfile = string.Empty; using (System.Diagnostics.Process process = new System.Diagnostics.Process()) { try { process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; if (Application.platform == RuntimePlatform.WindowsEditor) { scriptfile = System.IO.Path.GetTempPath() + "RestartUnity-" + System.Guid.NewGuid() + ".cmd"; System.IO.File.WriteAllText(scriptfile, generateWindowsRestartScript(executeMethod)); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = "/c start \"\" " + '"' + scriptfile + '"'; } else if (Application.platform == RuntimePlatform.OSXEditor) { scriptfile = System.IO.Path.GetTempPath() + "RestartUnity-" + System.Guid.NewGuid() + ".sh"; System.IO.File.WriteAllText(scriptfile, generateMacRestartScript(executeMethod)); process.StartInfo.FileName = "/bin/sh"; process.StartInfo.Arguments = '"' + scriptfile + "\" &"; } else if (Application.platform == RuntimePlatform.LinuxEditor) { scriptfile = System.IO.Path.GetTempPath() + "RestartUnity-" + System.Guid.NewGuid() + ".sh"; System.IO.File.WriteAllText(scriptfile, generateLinuxRestartScript(executeMethod)); process.StartInfo.FileName = "/bin/sh"; process.StartInfo.Arguments = '"' + scriptfile + "\" &"; } else { Debug.LogError("Unsupported Unity Editor: " + Application.platform); return; } process.Start(); if (isWindowsPlatform) { process.WaitForExit(Util.BaseConstants.PROCESS_KILL_TIME); } success = true; } catch (System.Exception ex) { string errorMessage = "Could restart Unity!" + System.Environment.NewLine + ex; Debug.LogError(errorMessage); } } if (success) { EditorApplication.Exit(0); } }
static void EnableBackendNet() { PlayerSettings.SetScriptingBackend(EditorUserBuildSettings.selectedBuildTargetGroup, ScriptingImplementation.WinRTDotNET); EditorApplication.Exit(0); }
public static void ExportCuratedSamples() { var oldBurst = EditorPrefs.GetBool("BurstCompilation"); EditorPrefs.SetBool("BurstCompilation", false); try { // Path to Project/Assets var assetsDir = Application.dataPath; var repoRoot = Directory.GetParent(Directory.GetParent(assetsDir).FullName).FullName; // Top level of where to store the samples var samplesDir = Path.Combine( repoRoot, k_MLAgentsPackageName, k_MLAgentsSamplesDirName); if (!Directory.Exists(samplesDir)) { Directory.CreateDirectory(samplesDir); } // Path to the examples dir in the project var examplesDir = Path.Combine(Application.dataPath, k_MLAgentsDir, k_MLAgentsExamplesDir); foreach (var exampleDirectory in Directory.GetDirectories(examplesDir)) { var mlAgentsSamplePath = Path.Combine(exampleDirectory, k_MLAgentsSampleFile); if (File.Exists(mlAgentsSamplePath)) { var sampleJson = JsonConvert.DeserializeObject <MLAgentsSampleJson>(File.ReadAllText(mlAgentsSamplePath)); Debug.Log(JsonConvert.SerializeObject(sampleJson)); foreach (var scene in sampleJson.scenes) { var scenePath = Path.Combine(exampleDirectory, scene); if (File.Exists(scenePath)) { // Create a Sample Directory var currentSampleDir = Directory.CreateDirectory(Path.Combine(samplesDir, Path.GetFileNameWithoutExtension(scenePath))); var scriptsPath = Path.Combine(exampleDirectory, k_MLAgentsScriptsDirName); Debug.Log($"Scene Path: {scenePath}"); var assets = new List <string> { scenePath.Substring(scenePath.IndexOf("Assets")) }; if (!Directory.Exists(Path.Combine(scriptsPath))) { scriptsPath = exampleDirectory; } scriptsPath = scriptsPath.Substring(scriptsPath.IndexOf("Assets")); foreach (var guid in AssetDatabase.FindAssets("t:Script", new[] { scriptsPath })) { var path = AssetDatabase.GUIDToAssetPath(guid); assets.Add(path); Debug.Log($"Adding Asset: {path}"); } var packageFilePath = Path.GetFileNameWithoutExtension(scenePath) + ".unitypackage"; AssetDatabase.ExportPackage(assets.ToArray(), Path.Combine(Application.dataPath, packageFilePath), ExportPackageOptions.IncludeDependencies | ExportPackageOptions.Recurse); // Move the .unitypackage into the samples folder. var packageFileFullPath = Path.Combine(Application.dataPath, packageFilePath); var packageInSamplePath = Path.Combine(currentSampleDir.FullName, packageFilePath); Debug.Log($"Moving {packageFileFullPath} to {packageInSamplePath}"); File.Move(packageFileFullPath, packageInSamplePath); // write the .sample.json file to the sample directory File.WriteAllText(Path.Combine(currentSampleDir.FullName, k_PackageSampleFile), JsonConvert.SerializeObject(new PackageSampleJson { description = sampleJson.description, displayName = sampleJson.displayName })); } } } } } catch (Exception e) { Debug.Log(e); EditorApplication.Exit(1); } EditorPrefs.SetBool("BurstCompilation", oldBurst); EditorApplication.Exit(0); }
//[MenuItem("ZenjectSamples/Enable Net 35")] static void EnableNet35() { PlayerSettings.scriptingRuntimeVersion = ScriptingRuntimeVersion.Legacy; PlayerSettings.SetApiCompatibilityLevel(EditorUserBuildSettings.selectedBuildTargetGroup, ApiCompatibilityLevel.NET_2_0_Subset); EditorApplication.Exit(0); }
static void EnableBackendIl2cpp() { PlayerSettings.SetScriptingBackend(EditorUserBuildSettings.selectedBuildTargetGroup, ScriptingImplementation.IL2CPP); EditorApplication.Exit(0); }
//[MenuItem("ZenjectSamples/Enable Net 46")] static void EnableNet46() { PlayerSettings.scriptingRuntimeVersion = ScriptingRuntimeVersion.Latest; PlayerSettings.SetApiCompatibilityLevel(EditorUserBuildSettings.selectedBuildTargetGroup, ApiCompatibilityLevel.NET_4_6); EditorApplication.Exit(0); }
/// <summary> /// 打包(生成)场景和 AssetBundle 资源 /// </summary> private static void GenerateAssets() { string targetPlatform = GetCmdLineArg("-targetPlatform"); string manifestPath = GetCmdLineArg("-manifestPath"); string outputDir = GetCmdLineArg("-outputDir"); string scenes = GetCmdLineArg("-scenes"); string outFilePath = GetCmdLineArg("-logFile").Replace("unity.log", "unity.out"); //string targetPlatform = "android"; //string manifestPath = "/Users/limylee/LOLO/unity/projects/ShibaInu/Tools/build/log/0/manifest.log"; //string outputDir = "/Users/limylee/LOLO/unity/projects/ShibaInu/Tools/build/ShibaInu/cache/"; //string scenes = "2,3"; //string outFilePath = "/Users/limylee/LOLO/unity/projects/ShibaInu/Tools/build/log/0/unity.out"; // 需要打包的场景索引列表 string[] buildScenes = scenes.Split(','); // 目标平台 BuildTarget buildTarget = default; switch (targetPlatform) { case "ios": buildTarget = BuildTarget.iOS; break; case "android": buildTarget = BuildTarget.Android; break; case "macos": buildTarget = BuildTarget.StandaloneOSX; break; case "windows": buildTarget = BuildTarget.StandaloneWindows; break; } // 解析打包清单 List <string> sceneList = new List <string>(); List <AssetBundleBuild> abbList = new List <AssetBundleBuild>(); using (StreamReader file = new StreamReader(manifestPath)) { string line; int phase = 1, index = 0, count = 0; AssetBundleBuild abb = default; List <string> assets = new List <string>(); while ((line = file.ReadLine()) != null) { switch (phase) { // lua case 1: if (count == 0) { count = int.Parse(line); } else { if (++index == count) { count = index = 0; phase++; } } break; // scene case 2: if (count == 0) { count = int.Parse(line); } else { sceneList.Add(line); if (++index == count) { count = index = 0; phase++; } } break; // AssetBundle case 3: if (count == 0) { count = int.Parse(line); } else { if (index == 0) { abb = new AssetBundleBuild { assetBundleName = line }; assets.Clear(); } else { assets.Add(line); } if (++index == count) { count = index = 0; abb.assetNames = assets.ToArray(); abbList.Add(abb); } } break; } } } // 打包场景 if (buildScenes.Length > 0 && buildScenes[0] != "") { DateTime timeScene = DateTime.Now; WriteOut(outFilePath, "build scene start"); string outputScene = outputDir + "scene/" + targetPlatform + "/"; if (!Directory.Exists(outputScene)) { Directory.CreateDirectory(outputScene); } foreach (string index in buildScenes) { DateTime time = DateTime.Now; string scene = sceneList[int.Parse(index)]; string[] levels = { scene }; string outputPath = outputScene + Path.GetFileName(scene); BuildReport report = BuildPipeline.BuildPlayer(levels, outputPath, buildTarget, BuildOptions.BuildAdditionalStreamedScenes); if (report.summary.result == BuildResult.Succeeded) { WriteOut(outFilePath, "build scene complete," + scene + "," + DateTime.Now.Subtract(time).TotalMilliseconds); } else { WriteOut(outFilePath, "build scene error," + scene + "," + report.summary.result); EditorApplication.Exit(1); return; } } WriteOut(outFilePath, "build scene all complete," + DateTime.Now.Subtract(timeScene).TotalMilliseconds); } // 打包 AssetBundle DateTime timeAB = DateTime.Now; WriteOut(outFilePath, "build assetbundle start"); string outputAB = outputDir + "assetbundle/" + targetPlatform + "/"; if (!Directory.Exists(outputAB)) { Directory.CreateDirectory(outputAB); } BuildPipeline.BuildAssetBundles(outputAB, abbList.ToArray(), BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.ChunkBasedCompression, buildTarget ); WriteOut(outFilePath, "build assetbundle complete," + DateTime.Now.Subtract(timeAB).TotalMilliseconds); // 写入 AssetBundle 依赖信息文件 string dependenciesFilePath = outputDir + "dependencies.json"; AssetBundle ab = AssetBundle.LoadFromFile(outputAB + targetPlatform); AssetBundleManifest manifest = (AssetBundleManifest)ab.LoadAsset("AssetBundleManifest"); string[] abList = manifest.GetAllAssetBundles(); using (StreamWriter writer = new StreamWriter(File.Open(dependenciesFilePath, FileMode.Create))) { writer.Write("{"); bool isFirst = true; foreach (string abPath in abList) { string[] depList = manifest.GetAllDependencies(abPath); if (depList.Length > 0) { if (isFirst) { isFirst = false; } else { writer.Write(","); } writer.Write("\n \"" + abPath + "\": ["); for (int i = 0; i < depList.Length; i++) { if (i != 0) { writer.Write(", "); } writer.Write("\"" + depList[i].Replace("\\", "/") + "\""); } writer.Write("]"); } } writer.Write("\n}"); } // }
static void OnChangedPlatform() { EditorApplication.SaveScene("Assets/PlatformChangeBackup.unity"); EditorApplication.Exit(0); }
public static void AndroidDevelopmentBuild() { string[] args = System.Environment.GetCommandLineArgs(); Debug.Log(" args len:" + args.Length); for (int i = 0; i < args.Length; i++) { Debug.Log(" args[" + i + "]:" + args[i]); } if (args.Length < 11) { EditorApplication.Exit(args.Length); } string projectPath = Application.dataPath; int slashIdx = 0; for (int i = 0; i < 3; i++) { slashIdx = projectPath.LastIndexOf("/"); projectPath = projectPath.Remove(slashIdx); } //args[args.Length - 4] is version projectPath += "/android_project/"; // + args[args.Length - 5] + "/" + args[args.Length - 2] + "_" + args[args.Length - 4]; System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(projectPath); if (!dirInfo.Exists) { dirInfo.Create(); } // Debug.Log(" apk path:" + apkPath ); BuildOptions buildOpt = BuildOptions.AcceptExternalModificationsToPlayer; //BuildOptions.None;//args[args.Length - 4] == "Dev" ? BuildOptions.Development : BuildOptions.None; PlayerSettings.Android.keystoreName = args[args.Length - 10]; PlayerSettings.Android.keystorePass = args[args.Length - 9]; PlayerSettings.Android.keyaliasName = args[args.Length - 8]; PlayerSettings.Android.keyaliasPass = args[args.Length - 7]; PlayerSettings.bundleVersion = args[args.Length - 1]; if (args[args.Length - 5] == "Publish") { PlayerSettings.Android.useAPKExpansionFiles = true; } else { PlayerSettings.Android.useAPKExpansionFiles = false; } //args[args.Length - 6] : branch name //args[args.Length - 5] : Dev or Release //args[args.Length - 4] : version //args[args.Length - 3] : target //args[args.Length - 2] : Google or Amazon //args[args.Length - 1] : Payment version for Google string preName = projectPath + args[args.Length - 6] + "_V" + args[args.Length - 4] + "_" + args[args.Length - 2] + "_" + args[args.Length - 5] + "_"; string apkFullName; StringBuilder sb = new StringBuilder(); for (var i = 0; i < PlayerSettings.bundleVersion.Length; i++) { if (PlayerSettings.bundleVersion[i] != '.') { sb.Append(PlayerSettings.bundleVersion[i]); } } string strVersionCode = sb.ToString(); string lastArg = args[args.Length - 3]; if (lastArg == "All" || lastArg == "ATC") { apkFullName = preName + "ATC"; PlayerSettings.Android.bundleVersionCode = System.Convert.ToInt32(strVersionCode + "05"); Debug.Log("bundleVersionCode:" + PlayerSettings.Android.bundleVersionCode); EditorUserBuildSettings.androidBuildSubtarget = AndroidBuildSubtarget.ATC; BuildPipeline.BuildPlayer(Scenes, apkFullName, BuildTarget.Android, buildOpt /*|BuildOptions.AcceptExternalModificationsToPlayer*/); } if (lastArg == "All" || lastArg == "DXT") { apkFullName = preName + "DXT"; PlayerSettings.Android.bundleVersionCode = System.Convert.ToInt32(strVersionCode + "04"); Debug.Log("bundleVersionCode:" + PlayerSettings.Android.bundleVersionCode); EditorUserBuildSettings.androidBuildSubtarget = AndroidBuildSubtarget.DXT; BuildPipeline.BuildPlayer(Scenes, apkFullName, BuildTarget.Android, buildOpt /*|BuildOptions.AcceptExternalModificationsToPlayer*/); } if (lastArg == "All" || lastArg == "ETC") { apkFullName = preName + "ETC"; PlayerSettings.Android.bundleVersionCode = System.Convert.ToInt32(strVersionCode + "03"); Debug.Log("bundleVersionCode:" + PlayerSettings.Android.bundleVersionCode); EditorUserBuildSettings.androidBuildSubtarget = AndroidBuildSubtarget.ETC2; BuildPipeline.BuildPlayer(Scenes, apkFullName, BuildTarget.Android, buildOpt /*|BuildOptions.AcceptExternalModificationsToPlayer*/); } if (lastArg == "All" || lastArg == "PVRTC") { apkFullName = preName + "PVRTC"; PlayerSettings.Android.bundleVersionCode = System.Convert.ToInt32(strVersionCode + "06"); Debug.Log("bundleVersionCode:" + PlayerSettings.Android.bundleVersionCode); EditorUserBuildSettings.androidBuildSubtarget = AndroidBuildSubtarget.PVRTC; BuildPipeline.BuildPlayer(Scenes, apkFullName, BuildTarget.Android, buildOpt /*|BuildOptions.AcceptExternalModificationsToPlayer*/); } }
public static void BuildApp() { string buildMode = "release"; string buildPlatform = "android"; string buildBackend = "mono"; string buildVersion = "0.0.0"; string appName = ""; string[] args = System.Environment.GetCommandLineArgs(); foreach (string oneArg in args) { if (oneArg != null && oneArg.Length > 0) { if (oneArg.StartsWith("--app")) { appName = oneArg.Replace("--app=", ""); } else if (oneArg.ToLower().Contains("--platform")) { buildPlatform = oneArg.Replace("--platform=", ""); } else if (oneArg.ToLower().Contains("--mode")) { buildMode = oneArg.Replace("--mode=", ""); } else if (oneArg.ToLower().Contains("--backend")) { buildBackend = oneArg.Replace("--backend=", ""); } else if (oneArg.ToLower().Contains("--version")) { buildVersion = oneArg.Replace("--version=", ""); } } } BuildOptions buildOption = BuildOptions.None; if (buildBackend == "il2cpp") // TODO no use { buildOption = BuildOptions.Il2CPP; } if (buildMode == "debug") { buildOption |= BuildOptions.Development; buildOption |= BuildOptions.AllowDebugging; buildOption |= BuildOptions.ConnectWithProfiler; } if (buildPlatform == "android") { PlayerSettings.bundleVersion = buildVersion; VersionCode GameVersion = new VersionCode(buildVersion); PlayerSettings.Android.bundleVersionCode = GameVersion.GetBundleVersionCode();// ios上无此选项 Debug.Log("已将版本号修改为" + buildVersion); //PlayerSettings.Android.keystorePass = "******"; //PlayerSettings.Android.keyaliasPass = "******"; UnityEngine.Debug.Log("编译Apk开始 " + appName); string buildError = BuildPipeline.BuildPlayer(scenes, appName, BuildTarget.Android, buildOption); if (string.IsNullOrEmpty(buildError)) { UnityEngine.Debug.Log("编译Apk成功 " + appName); EditorApplication.Exit(0); } else { UnityEngine.Debug.Log("编译Apk失败 " + appName); EditorApplication.Exit(1); } } else { if (!Directory.Exists(appName)) { Directory.CreateDirectory(appName); } //if (Directory.Exists(productName)) // Directory.Delete(productName); UnityEngine.Debug.Log("生成iOS XCode工程开始 " + appName); BuildPipeline.BuildPlayer(scenes, appName, BuildTarget.iOS, buildOption); UnityEngine.Debug.Log("生成iOS XCode工程完成 " + appName); } }
public static void Build() { // TODO: may get option from JSON written by pipeline var args = Environment.GetCommandLineArgs(); var buildOutputPath = GetCommandLineArgumentValue(args, "BuildOutputPath"); var developmentBuild = false; var devbuildParseResult = Boolean.TryParse(GetCommandLineArgumentValue(args, "DevelopmentBuild"), out developmentBuild); var allActiveScenes = GetAllActivatedScenes(); var activeTarget = EditorUserBuildSettings.activeBuildTarget; var selectedtargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup; var outputPath = AddBuildTargetOutputFileExtension(buildOutputPath); var dbg = "Aquired build options:\n\tBuild scenes (" + allActiveScenes.Length + "):\n"; for (int i = 0; i < allActiveScenes.Length; i++) { dbg += "\t\t- " + allActiveScenes[i] + "\n"; } dbg += "\tTarget: " + activeTarget + " | " + selectedtargetGroup; dbg += "\nOutput path: " + buildOutputPath; dbg += "\nOutput with extension: " + outputPath; dbg += "\nDevemlopment Build: " + developmentBuild; Debug.Log(dbg); // These options make append to project and auto play + build var playerOptions = BuildOptions.AcceptExternalModificationsToPlayer | BuildOptions.AutoRunPlayer; // if dev build also enable script debugging if (developmentBuild) { playerOptions = playerOptions | BuildOptions.Development | BuildOptions.AllowDebugging; } var buildPlayerOptions = new BuildPlayerOptions { scenes = allActiveScenes, target = activeTarget, targetGroup = selectedtargetGroup, locationPathName = outputPath, options = playerOptions, }; // AddressableAssetSettings.BuildPlayerContent(); var buildReport = default(BuildReport); buildReport = BuildPipeline.BuildPlayer(buildPlayerOptions); Debug.Log(string.Format("Build {0} in {1} seconds", buildReport.summary.result.ToString(), buildReport.summary.totalTime.Seconds)); if (buildReport.summary.result == BuildResult.Succeeded) { EditorApplication.Exit(0); } // else EditorApplication.Exit(1); }
/// <summary> /// Builds a given build collection from command line. Call this method directly from the command line using Unity in headless mode. /// <https://docs.unity3d.com/Documentation/Manual/CommandLineArguments.html> /// /// Provide `collection` parameter to your command line build to specify the collection you want to build. /// All selected build processes within the collection will be build. /// /// Example: -collection=Assets/New\ BuildCollection.asset /// </summary> public static void BuildFromCommandLine() { bool batchMode = false; string[] arguments = System.Environment.GetCommandLineArgs(); string[] availableArgs = { "-batchmode", "-collection=", "-android-sdk=", "-buildTag=", "-buildAll", "-commitID=", "-tagName=" }; string collectionPath = ""; string androidSdkPath = ""; string buildTag = ""; string commitID = ""; string tagName = ""; bool buildAll = false; foreach (var s in arguments) { if (s.StartsWith("-batchmode")) { batchMode = true; Debug.Log("UBS process started in batchmode!"); } if (s.StartsWith("-collection=")) { collectionPath = s.Substring(availableArgs[1].Length); } if (s.StartsWith("-android-sdk=")) { androidSdkPath = s.Substring(availableArgs[2].Length); } if (s.StartsWith("-buildTag=")) { buildTag = s.Substring(availableArgs[3].Length); } if (s.StartsWith("-buildAll")) { buildAll = true; Debug.Log("Selection override: building whole collection!"); } if (s.StartsWith("-commitID=")) { commitID = s.Substring(availableArgs[5].Length); } if (s.StartsWith("-tagName=")) { tagName = s.Substring(availableArgs[6].Length); } } if (collectionPath == null) { Debug.LogError("NO BUILD COLLECTION SET"); return; } if (!string.IsNullOrEmpty(androidSdkPath)) { EditorPrefs.SetString("AndroidSdkRoot", androidSdkPath); Debug.Log("Set Android SDK root to: " + androidSdkPath); } if (!string.IsNullOrEmpty(commitID)) { EditorPrefs.SetString("commitID", commitID); Debug.Log("Set commitID to: " + commitID); } if (!string.IsNullOrEmpty(tagName)) { EditorPrefs.SetString("tagName", tagName); Debug.Log("Set tagName to: " + tagName); } Debug.Log("Loading Build Collection: " + collectionPath); // Load Build Collection BuildCollection collection = AssetDatabase.LoadAssetAtPath(collectionPath, typeof(BuildCollection)) as BuildCollection; // Run Create Command Create(collection, false, batchMode, buildAll, buildTag); UBSProcess process = LoadUBSProcess(); try { while (true) { process.MoveNext(); Debug.Log("Wait.."); Debug.Log("Process state: " + process.CurrentState); if (process.CurrentState == UBSState.done) { return; } } }catch (Exception pException) { Debug.LogError("Build failed due to exception: "); Debug.LogException(pException); EditorApplication.Exit(1); } }
static void BuildSamples() { string resultDir = GetResultDir(); Console.WriteLine("Result Dir: " + resultDir); var sampleName = "Unknown Sample"; var projSamplesDir = new DirectoryInfo("Assets/Sample"); if (projSamplesDir.Exists) { // Use the directory name in the samples directory, if it exists sampleName = projSamplesDir.GetDirectories()[0].Name; } else { // Otherwise use the current folder as the project name projSamplesDir = new DirectoryInfo("Assets"); sampleName = new DirectoryInfo(".").Name; } PlayerSettings.colorSpace = ColorSpace.Linear; FeatureHelpers.RefreshFeatures(EditorUserBuildSettings.selectedBuildTargetGroup); foreach (var setup in buildTargetSetup) { if (setup.sampleRegex != null && !setup.sampleRegex.Match(sampleName).Success) { continue; } if (EditorUserBuildSettings.activeBuildTarget != setup.buildTarget) { continue; } string outputDir = Path.Combine(resultDir, setup.buildTarget.ToString()); string identifier = "com.openxr." + sampleName + "." + setup.outputPostfix; PlayerSettings.SetApplicationIdentifier(setup.targetGroup, identifier); PlayerSettings.productName = "OpenXR " + sampleName + " " + setup.outputPostfix; Console.WriteLine("=========== Setting up player settings (changing graphics apis)"); string outputFile = Path.Combine(outputDir, PlayerSettings.productName + GetBuildFileExt(setup.buildTarget)); setup.setupPlayerSettings(outputFile, identifier); // Get the list of scenes set in build settings in the project var scenes = EditorBuildSettings.scenes.Where(s => s.enabled).Select(s => s.path).ToArray(); // If there aren't any, just build all of the scenes found in the sample if (scenes.Length == 0) { scenes = Directory.GetFiles(projSamplesDir.FullName, "*.unity", SearchOption.AllDirectories); } BuildPlayerOptions buildOptions = new BuildPlayerOptions { scenes = scenes, target = setup.buildTarget, targetGroup = setup.targetGroup, locationPathName = outputFile, }; Console.WriteLine($"=========== Building {sampleName} {setup.buildTarget}_{setup.outputPostfix}"); var report = BuildPipeline.BuildPlayer(buildOptions); Console.WriteLine($"=========== Build Result {sampleName} {setup.buildTarget}_{setup.outputPostfix} {report.summary.result}"); if (report.summary.result == BuildResult.Failed) { EditorApplication.Exit(1); } } }
private static void DoBuildIOSInternal(iOSBuildType buildType, iOSSdkVersion sdkVersion) { Debug.Log("Building iOS..."); CurrentGroup = BuildTargetGroup.iOS; var xrGeneralSettings = XRGeneralSettingsPerBuildTarget.XRGeneralSettingsForBuildTarget(BuildTargetGroup.iOS); var prevCompilerConfiguration = PlayerSettings.GetIl2CppCompilerConfiguration(BuildTargetGroup.iOS); var prevScriptingDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.iOS); var prev_sdkVersion = PlayerSettings.iOS.sdkVersion; var isDebug = !(buildType == iOSBuildType.Debug); var disabledARKit = false; using var revertSettings = new Disposable(() => { CurrentGroup = null; PlayerSettings.iOS.sdkVersion = prev_sdkVersion; PlayerSettings.SetIl2CppCompilerConfiguration(BuildTargetGroup.iOS, prevCompilerConfiguration); if (!Application.isBatchMode) { PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.iOS, prevScriptingDefines); } if (disabledARKit) { XRPackageMetadataStore.AssignLoader( xrGeneralSettings.AssignedSettings, typeof(UnityEngine.XR.ARKit.ARKitLoader).FullName, BuildTargetGroup.iOS); } }); var compilerConfiguration = isDebug ? Il2CppCompilerConfiguration.Debug : Il2CppCompilerConfiguration.Master; PlayerSettings.SetIl2CppCompilerConfiguration(BuildTargetGroup.iOS, compilerConfiguration); PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.iOS, ProcessDefines(prevScriptingDefines, isDebug)); PlayerSettings.iOS.sdkVersion = sdkVersion; if (sdkVersion == iOSSdkVersion.SimulatorSDK && xrGeneralSettings.AssignedSettings.activeLoaders.Any(m => m.GetType() == typeof(UnityEngine.XR.ARKit.ARKitLoader))) { // ARKit is not supported on iOS Simulator - disable it temporairly XRPackageMetadataStore.RemoveLoader( xrGeneralSettings.AssignedSettings, typeof(UnityEngine.XR.ARKit.ARKitLoader).FullName, BuildTargetGroup.iOS); disabledARKit = true; } string exportPath = Path.GetFullPath(Path.Combine(ProjectPath, "../../ios/UnityExport")); string buildPath = iosBuildPath; if (Directory.Exists(buildPath)) { Directory.Delete(buildPath, true); } EditorUserBuildSettings.iOSBuildConfigType = buildType; try { var options = (buildType == iOSBuildType.Debug ? BuildOptions.AllowDebugging : BuildOptions.None); var report = BuildPipeline.BuildPlayer( GetEnabledScenes(), buildPath, BuildTarget.iOS, options ); if (report.summary.result != BuildResult.Succeeded) { throw new Exception("Build failed"); } // Clear UnityExport DeleteFolderContent(exportPath); // Copy build output to UnityExport Debug.Log("Copy to UnityExport"); CopyDirectory( buildPath, exportPath, mergeDirectories: false, overwriteFiles: true); } catch (Exception e) { Debug.Log("Export failed!"); if (Application.isBatchMode) { Debug.LogError(e); EditorApplication.Exit(-1); } else { throw; } } finally { Debug.Log("Export completed!"); if (Application.isBatchMode) { EditorApplication.Exit(0); } } }
public static void Run() { if (string.IsNullOrEmpty(POST_URL)) { return; } AssetDatabase.Refresh(); var logPath = $"{Application.dataPath}/../build.log"; var fs = new FileStream(logPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var sb = new StringBuilder(); var errorExist = false; using (var sr = new StreamReader(fs)) { while (!sr.EndOfStream) { var s = sr.ReadLine(); if (s != null) { if (errorExist) { if (s.Contains("CompilerOutput:-stderr")) { errorExist = false; } else { sb.AppendLine(s); } } if (s.Contains("compilationhadfailure")) { errorExist = true; } } else { if (sb.Length > 0) { var json = new JObject { { "msg_type", "text" }, { "content", new JObject { { "text", sb.ToString() } } } }; var req = WebRequest.CreateHttp(POST_URL); req.Method = "POST"; req.ContentType = "application/json"; var stream = req.GetRequestStream(); var buffer = Encoding.UTF8.GetBytes(json.ToString(Formatting.None)); stream.Write(buffer, 0, buffer.Length); stream.Flush(); var response = req.GetResponse(); stream = response.GetResponseStream(); var readByteCount = 0; buffer = new byte[response.ContentLength]; while (readByteCount < response.ContentLength) { readByteCount += stream.Read(buffer, readByteCount, buffer.Length - readByteCount); } var res = Encoding.UTF8.GetString(buffer); var jres = JObject.Parse(res); if (jres["errmsg"] != null && jres["errmsg"].Value <string>() != "ok") { Debug.LogError($"Response error : {res}"); } } errorExist = false; sb.Clear(); } } } EditorApplication.Exit(0); }
public static void DoBuildUWP() { try { CurrentGroup = BuildTargetGroup.WSA; string exportPath = Path.GetFullPath(Path.Combine(ProjectPath, "../../windows/UnityExport")); DeleteFolderContent(exportPath); EditorUserBuildSettings.wsaBuildAndRunDeployTarget = WSABuildAndRunDeployTarget.LocalMachine; // EditorUserBuildSettings.wsaGenerateReferenceProjects = true; EditorUserBuildSettings.wsaSubtarget = WSASubtarget.PC; EditorUserBuildSettings.wsaUWPBuildType = WSAUWPBuildType.XAML; EditorUserBuildSettings.buildScriptsOnly = false; EditorUserBuildSettings.installInBuildFolder = false; // EditorUserBuildSettings.SetWSADotNetNative(WSABuildType.Master, false); string oldScriptingDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.WSA); string newScriptingDefines = ProcessDefines(oldScriptingDefines, true); PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.WSA, newScriptingDefines); try { var options = BuildOptions.AcceptExternalModificationsToPlayer; var report = BuildPipeline.BuildPlayer( GetEnabledScenes(), exportPath, BuildTarget.WSAPlayer, options ); if (report.summary.result != BuildResult.Succeeded) { throw new Exception("Build failed"); } } catch (Exception e) { Debug.Log("Export failed!"); if (Application.isBatchMode) { Debug.LogError(e); EditorApplication.Exit(-1); } else { throw; } } finally { Debug.Log("Export completed!"); if (!Application.isBatchMode) { PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.WSA, oldScriptingDefines); } else { EditorApplication.Exit(0); } } } finally { CurrentGroup = null; } }
public static void Quit2() { // Environment.Exit(0); EditorApplication.Exit(0); }
private static void DoBuildAndroidInternal(Il2CppCompilerConfiguration compilerConfiguration) { Debug.Log("Building Android..."); CurrentGroup = BuildTargetGroup.Android; var prevCompilerConfiguration = PlayerSettings.GetIl2CppCompilerConfiguration(BuildTargetGroup.Android); var prevScriptingDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android); var isDebug = !(compilerConfiguration == Il2CppCompilerConfiguration.Master); using var revertSettings = new Disposable(() => { CurrentGroup = null; PlayerSettings.SetIl2CppCompilerConfiguration(BuildTargetGroup.Android, prevCompilerConfiguration); if (!Application.isBatchMode) { PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, prevScriptingDefines); } }); PlayerSettings.SetIl2CppCompilerConfiguration(BuildTargetGroup.Android, compilerConfiguration); PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, ProcessDefines(prevScriptingDefines, isDebug)); string exportPath = Path.GetFullPath(Path.Combine(ProjectPath, "../../android/UnityExport")); string buildPath = androidBuildPath; if (Directory.Exists(buildPath)) { Directory.Delete(buildPath, true); } EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle; EditorUserBuildSettings.exportAsGoogleAndroidProject = true; try { var options = (compilerConfiguration == Il2CppCompilerConfiguration.Debug ? BuildOptions.AllowDebugging : BuildOptions.None); var report = BuildPipeline.BuildPlayer( GetEnabledScenes(), buildPath, BuildTarget.Android, options); if (report.summary.result != BuildResult.Succeeded) { throw new Exception("Build failed"); } // Modify build.gradle { Debug.Log("Patch launcher/build.gradle"); var launcher_build_file = Path.Combine(buildPath, "launcher/build.gradle"); var launcher_build_text = File.ReadAllText(launcher_build_file); Debug.Log("Patch unityLibrary/build.gradle"); var build_file = Path.Combine(buildPath, "unityLibrary/build.gradle"); var build_text = File.ReadAllText(build_file); build_text = build_text.Replace("com.android.application", "com.android.library"); build_text = Regex.Replace(build_text, @"\n.*applicationId '.+'.*\n", "\n"); build_text = Regex.Replace(build_text, @":unityLibrary", ":UnityExport"); build_text = Regex.Replace(build_text, @"dependencies\s+\{[^\}]+\}", d => { var value = d.Value; value = Regex.Replace(value, @"(\s+)(implementation project)([^\n]+)'([^\n]+)('[^\n]+)", m => m.Groups[1].Value + "api project(':" + m.Groups[4].Value + m.Groups[5].Value); value = Regex.Replace(value, @"(\s+)(compile)([^\n]+\n)", m => m.Groups[1].Value + "api" + m.Groups[3].Value); value = Regex.Replace(value, @"(\s+)(implementation)([^\n]+\n)", m => m.Groups[1].Value + "api" + m.Groups[3].Value); value = Regex.Replace(value, @"(\s+)api.+appcenter-release.+", m => m.Groups[1].Value + "api 'com.microsoft.appcenter:appcenter:+'"); value = Regex.Replace(value, @"(\s+)api.+appcenter-analytics-release.+", m => m.Groups[1].Value + "api 'com.microsoft.appcenter:appcenter-analytics:+'"); value = Regex.Replace(value, @"(\s+)api.+appcenter-crashes-release.+", m => m.Groups[1].Value + "api 'com.microsoft.appcenter:appcenter-crashes:+'"); return(value); }); build_text = Regex.Replace(build_text, @"\s*def BuildIl2Cpp\([^\(\)\{\}]*\)\s*\{", d => { var builder = new StringBuilder(); builder.AppendLine(); builder.AppendLine("def getUnityDir() {"); builder.AppendLine(" Properties local = new Properties()"); builder.AppendLine(" local.load(new FileInputStream(\"${rootDir}/local.properties\"))"); builder.AppendLine(" return local.getProperty('unity.dir')"); builder.AppendLine("}"); builder.AppendLine(d.Groups[0].Value); builder.AppendLine(" String il2cppPath = getUnityDir();"); builder.AppendLine(" if (!il2cppPath) {"); builder.AppendLine(" il2cppPath = workingDir + \"/src/main/Il2CppOutputProject\""); builder.AppendLine(" }"); return(builder.ToString()); }); build_text = Regex.Replace( build_text, "commandLine\\(workingDir\\s*\\+\\s*\"/src/main/Il2CppOutputProject/IL2CPP/build/deploy/netcoreapp3\\.1/il2cpp\\.exe\",", "commandLine(il2cppPath + \"/IL2CPP/build/deploy/netcoreapp3.1/il2cpp\","); build_text = CopyGradleBlock( launcher_build_text, build_text, @"(\s+aaptOptions\s+\{[^\}]+\})", @"(android\s+\{)(([^\}]+)+)", overwrite: false); build_text = CopyGradleBlock( launcher_build_text, build_text, @"(\s+buildTypes\s+\{([^\{\}]+\{[^\{\}]+\}[^\{\}]+)+\})", @"(android\s+\{)(([^\}]+)+)", overwrite: false); File.WriteAllText(build_file, build_text); } // Modify AndroidManifest.xml Debug.Log("Patch AndroidManifest.xml"); var manifest_file = Path.Combine(buildPath, "unityLibrary/src/main/AndroidManifest.xml"); var manifest_text = File.ReadAllText(manifest_file); manifest_text = Regex.Replace(manifest_text, @"\s*<uses-sdk[^>]*/>", ""); manifest_text = Regex.Replace(manifest_text, @"<application .*>", "<application>"); Regex regex = new Regex(@"<activity.*>(\s|\S)+?</activity>", RegexOptions.Multiline); manifest_text = regex.Replace(manifest_text, ""); File.WriteAllText(manifest_file, manifest_text); // Clear UnityExport DeleteFolderContent(exportPath); // Copy build output to UnityExport Debug.Log("Copy to UnityExport"); CopyDirectory( buildPath, exportPath, mergeDirectories: false, overwriteFiles: true); // Copy local.properties Debug.Log("Copy local.properties"); CopyFile( Path.Combine(exportPath, "local.properties"), Path.Combine(exportPath, "../local.properties"), overwriteFiles: true); // Copy gradle.properties Debug.Log("Copy gradle.properties"); CopyFile( Path.Combine(exportPath, "gradle.properties"), Path.Combine(exportPath, "unityLibrary/gradle.properties"), overwriteFiles: true); // Copy some files from 'launcher' project Debug.Log("Copy resources"); CopyDirectory( Path.Combine(exportPath, "launcher/src/main/res"), Path.Combine(exportPath, "unityLibrary/src/main/res"), mergeDirectories: true, overwriteFiles: true); } catch (Exception e) { Debug.Log("Export failed!"); if (Application.isBatchMode) { Debug.LogError(e); EditorApplication.Exit(-1); } else { throw; } } finally { Debug.Log("Export completed!"); if (Application.isBatchMode) { EditorApplication.Exit(0); } } }
/// <summary> /// 将Lua/*.lua文件复制为LuaGen/*.lua.txt文件. /// </summary> private static void UpdateLuaScripts(bool bLuajit = true) { bool bSuccess = true; if (Directory.Exists(PATH_OF_LUA + "Gen")) { FileSystem.ClearPath(PATH_OF_LUA + "Gen", false); } else { FileSystem.CreatePath(PATH_OF_LUA + "Gen"); } AssetDatabase.Refresh(); if (bLuajit) { string tool_path = ""; string ROOT_PATH = Application.dataPath; ROOT_PATH = ROOT_PATH.Replace("\\", "/"); ROOT_PATH = ROOT_PATH.Substring(0, ROOT_PATH.LastIndexOf("/") + 1); tool_path = ROOT_PATH + "Tools/buildLua.bat"; string full_path_lua = string.Format("{0}{1}/", ROOT_PATH, PATH_OF_LUA); Process proc; try { proc = new Process(); proc.StartInfo.FileName = tool_path; proc.StartInfo.Arguments = string.Format("{0} {1} {2} {3}", PATH_OF_LUA, full_path_lua.Length, ROOT_PATH, bLuajit.ToString().ToLower());//this is argument proc.StartInfo.CreateNoWindow = false; proc.Start(); proc.WaitForExit(); } catch (Exception ex) { bSuccess = false; Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString()); } AssetDatabase.Refresh(); AssetDatabase.SaveAssets(); if (!bSuccess) { //failed to build lua scripts, exit now and force set jenkins build flag as unstable EditorApplication.Exit(1); } } else { List <string> subFiles = new List <string>(); subFiles = CustomTool.FileSystem.GetSubFiles(PATH_OF_LUA); string from_set = PATH_OF_LUA; string to_set = PATH_OF_LUA + "Gen"; foreach (var file in subFiles) { // if (file.Contains("sproto")) { string BundlePath = to_set + "/" + file + GameHelper.LUA_FILENAME_EXTENSION; if (!Directory.Exists(Path.GetDirectoryName(BundlePath))) { FileSystem.CreatePath(Path.GetDirectoryName(BundlePath)); } if (File.Exists(from_set + "/" + file)) { FileUtil.ReplaceFile(from_set + "/" + file, BundlePath); } else { // UnityEngine.Debug.LogError("Failed cooking bundle:: " + file); } } } } AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); }
private IEnumerator RunTestsCR() { while (_queuedTests.Count > 0) { Type testType = _queuedTests.Dequeue(); _activeTest = Activator.CreateInstance(testType) as UnitTest; if (_activeTest != null) { if ((string.IsNullOrEmpty(_activeTest.ProjectToTest()) && string.IsNullOrEmpty(ProjectToTest)) || (_activeTest.ProjectToTest() == ProjectToTest) || (!string.IsNullOrEmpty(_activeTest.ProjectToTest()) && !string.IsNullOrEmpty(ProjectToTest) && ProjectToTest.ToLower().Contains(_activeTest.ProjectToTest().ToLower()))) { Log.Status("UnitTestManager", "STARTING UnitTest {0} ...", testType.Name); // wait for the test to complete.. bool bTestException = true; DateTime startTime = DateTime.Now; try { IEnumerator e = _activeTest.RunTest(); while (e.MoveNext()) { if (_activeTest.TestFailed) { break; } yield return(null); if ((DateTime.Now - startTime).TotalSeconds > TestTimeout) { Log.Error("UnitTestManager", "UnitTest {0} has timed out.", testType.Name); _activeTest.TestFailed = true; break; } } bTestException = false; if (_activeTest.TestFailed) { Log.Error("UnitTestManager", "... UnitTest {0} FAILED.", testType.Name); TestsFailed += 1; } else { Log.Status("UnitTestManager", "... UnitTest {0} COMPLETED.", testType.Name); TestsComplete += 1; } } finally { } if (bTestException) { Log.Error("UnitTestManager", "... UnitTest {0} threw exception.", testType.Name); TestsFailed += 1; } } else { //do nothing - because the test we have is not in the project we are testing } } else { Log.Error("UnitTestManager", "Failed to instantiate test {0}.", testType.Name); TestsFailed += 1; } } if (OnTestCompleteCallback != null) { OnTestCompleteCallback(); } if (TestsComplete == 0 && TestsFailed == 0) { Log.Status("UnitTestManager", "Nothing to Test"); } else { Log.Status("UnitTestManager", "Tests Completed: {0}, Tests Failed: {1}", TestsComplete, TestsFailed); } #if UNITY_EDITOR if (QuitOnTestsComplete) { EditorApplication.Exit(TestsFailed > 0 ? 1 : 0); } #endif }
private static void ExitAndCopy() { Copy(); EditorApplication.Exit(0); }
/// <summary>Restart Unity.</summary> /// <param name="executeMethod">Executed method after the restart (optional)</param> public static void RestartUnity(string executeMethod = "") { UnityEditor.SceneManagement.EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); bool success = false; using (System.Diagnostics.Process process = new System.Diagnostics.Process()) { try { process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; string scriptfile; switch (Application.platform) { case RuntimePlatform.WindowsEditor: scriptfile = $"{System.IO.Path.GetTempPath()}RestartUnity-{System.Guid.NewGuid()}.cmd"; System.IO.File.WriteAllText(scriptfile, generateWindowsRestartScript(executeMethod)); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = $"/c start \"\" \"{scriptfile}\""; break; case RuntimePlatform.OSXEditor: scriptfile = $"{System.IO.Path.GetTempPath()}RestartUnity-{System.Guid.NewGuid()}.sh"; System.IO.File.WriteAllText(scriptfile, generateMacRestartScript(executeMethod)); process.StartInfo.FileName = "/bin/sh"; process.StartInfo.Arguments = $"\"{scriptfile}\" &"; break; case RuntimePlatform.LinuxEditor: scriptfile = $"{System.IO.Path.GetTempPath()}RestartUnity-{System.Guid.NewGuid()}.sh"; System.IO.File.WriteAllText(scriptfile, generateLinuxRestartScript(executeMethod)); process.StartInfo.FileName = "/bin/sh"; process.StartInfo.Arguments = $"\"{scriptfile}\" &"; break; default: Debug.LogError($"Unsupported Unity Editor: {Application.platform}"); return; } process.Start(); if (isWindowsEditor) { process.WaitForExit(Util.BaseConstants.PROCESS_KILL_TIME); } success = true; } catch (System.Exception ex) { string errorMessage = $"Could restart Unity: {ex}"; Debug.LogError(errorMessage); } } if (success) { EditorApplication.Exit(0); } }
static void CloseUnity() { EditorApplication.Exit(0); }
private IEnumerator RunTestsCR() { while (m_QueuedTests.Count > 0) { Type testType = m_QueuedTests.Dequeue(); m_ActiveTest = Activator.CreateInstance(testType) as UnitTest; if (m_ActiveTest != null) { Log.Status("UnitTestManager", "STARTING UnitTest {0} ...", testType.Name); // wait for the test to complete.. bool bTestException = true; DateTime startTime = DateTime.Now; try { IEnumerator e = m_ActiveTest.RunTest(); while (e.MoveNext()) { if (m_ActiveTest.TestFailed) { break; } yield return(null); if ((DateTime.Now - startTime).TotalSeconds > TEST_TIMEOUT) { Log.Error("UnitTestManager", "UnitTest {0} has timed out.", testType.Name); m_ActiveTest.TestFailed = true; break; } } bTestException = false; if (m_ActiveTest.TestFailed) { Log.Error("UnitTestManager", "... UnitTest {0} FAILED.", testType.Name); TestsFailed += 1; } else { Log.Status("UnitTestManager", "... UnitTest {0} COMPLETED.", testType.Name); TestsComplete += 1; } } finally {} if (bTestException) { Log.Error("UnitTestManager", "... UnitTest {0} threw exception.", testType.Name); TestsFailed += 1; } } else { Log.Error("UnitTestManager", "Failed to instantiate test {0}.", testType.Name); TestsFailed += 1; } } if (OnTestCompleteCallback != null) { OnTestCompleteCallback(); } Log.Status("UnitTestManager", "Tests Completed: {0}, Tests Failed: {1}", TestsComplete, TestsFailed); #if UNITY_EDITOR if (QuitOnTestsComplete) { EditorApplication.Exit(TestsFailed > 0 ? 1 : 0); } #endif }