public override void Draw(int aID) { if (dataControlList.index != -1) { var unitySceneDataControl = dataControlList.list[dataControlList.index] as UnitySceneDataControl; EditorGUI.BeginChangeCheck(); var scene = AssetDatabase.LoadAssetAtPath <SceneAsset>(unitySceneDataControl.Scene); var newScene = EditorGUILayout.ObjectField("Scene", scene, typeof(SceneAsset), true); if (EditorGUI.EndChangeCheck()) { unitySceneDataControl.Scene = AssetDatabase.GetAssetOrScenePath(newScene); } var isInBuildSettings = IsInBuildSettings(newScene); if (isInBuildSettings) { EditorGUILayout.HelpBox("UnityPlugin.SceneWindow.InBuildSettings".Traslate(), MessageType.Info); } else { EditorGUILayout.HelpBox("UnityPlugin.SceneWindow.SceneNotInBuildSettings".Traslate(), MessageType.Error); } using (new EditorGUI.DisabledScope(!newScene || isInBuildSettings)) { if (GUILayout.Button("UnityPlugin.SceneWindow.AddSceneToBuildSettings".Traslate())) { var buildSettingsScene = new EditorBuildSettingsScene(unitySceneDataControl.Scene, true); EditorBuildSettings.scenes = new List <EditorBuildSettingsScene>(EditorBuildSettings.scenes) { buildSettingsScene }.ToArray(); } } } else { GUILayout.Label("Select an scene in the left"); var scene1GUID = AssetDatabase.GUIDToAssetPath(AssetDatabase.FindAssets("_Scene1")[0]); var scene1 = AssetDatabase.LoadAssetAtPath(scene1GUID, typeof(SceneAsset)); var isInBuildSettings = IsInBuildSettings(scene1); if (isInBuildSettings) { EditorGUILayout.HelpBox("UnityPlugin.SceneWindow.MainSceneInBuildSettings".Traslate(), MessageType.Info); } else { EditorGUILayout.HelpBox("UnityPlugin.SceneWindow.MainSceneNotInBuildSettings".Traslate(), MessageType.Error); } using (new EditorGUI.DisabledScope(!scene1 || isInBuildSettings)) { if (GUILayout.Button("UnityPlugin.SceneWindow.AddSceneToBuildSettings".Traslate())) { var buildSettingsScene = new EditorBuildSettingsScene(scene1GUID, true); EditorBuildSettings.scenes = new List <EditorBuildSettingsScene>(EditorBuildSettings.scenes) { buildSettingsScene }.ToArray(); } } } }
void ProcessAllBuilds() { //if (keystorePath != "") //{ // PlayerSettings.Android.keystoreName = keystorePath; // PlayerSettings.Android.keystorePass = keystorePass; // PlayerSettings.Android.keyaliasName = keyaliasName; // PlayerSettings.Android.keyaliasPass = keyaliasPass; //} textureConfigsARM = new List <MobileTextureSubtarget>(); textureConfigsX86 = new List <MobileTextureSubtarget>(); //textureConfigsFAT = new List<MobileTextureSubtarget>(); if (buildARM) { for (int i = 0; i < buildARMTextures.Length; i++) { if (buildARMTextures[i]) { textureConfigsARM.Add(texturesTarget[i]); } } System.IO.Directory.CreateDirectory(savePath + "/" + AndroidTargetDevice.ARMv7.ToString()); for (int j = 0; j < textureConfigsARM.Count; j++) { PlayerSettings.Android.targetDevice = AndroidTargetDevice.ARMv7; EditorUserBuildSettings.androidBuildSubtarget = textureConfigsARM[j]; BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions(); PlayerSettings.Android.bundleVersionCode = bundleVersionCode + 10 + j; string path = savePath + "/" + AndroidTargetDevice.ARMv7.ToString() + "/" + Application.productName + " - " + PlayerSettings.Android.bundleVersionCode.ToString() + " - " + textureConfigsARM[j].ToString() + ".apk"; buildPlayerOptions.scenes = EditorBuildSettingsScene.GetActiveSceneList(EditorBuildSettings.scenes); buildPlayerOptions.locationPathName = path; buildPlayerOptions.target = BuildTarget.Android; string buildResult = BuildPipeline.BuildPlayer(buildPlayerOptions); } } if (buildX86) { for (int i = 0; i < buildX86Textures.Length; i++) { if (buildX86Textures[i]) { textureConfigsX86.Add(texturesTarget[i]); } } System.IO.Directory.CreateDirectory(savePath + "/" + AndroidTargetDevice.x86.ToString()); for (int j = 0; j < textureConfigsX86.Count; j++) { PlayerSettings.Android.targetDevice = AndroidTargetDevice.x86; EditorUserBuildSettings.androidBuildSubtarget = textureConfigsX86[j]; BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions(); PlayerSettings.Android.bundleVersionCode = bundleVersionCode + 20 + j; string path = savePath + "/" + AndroidTargetDevice.x86.ToString() + "/" + Application.productName + " - " + PlayerSettings.Android.bundleVersionCode.ToString() + " - " + textureConfigsX86[j].ToString() + ".apk"; buildPlayerOptions.scenes = EditorBuildSettingsScene.GetActiveSceneList(EditorBuildSettings.scenes); buildPlayerOptions.locationPathName = path; buildPlayerOptions.target = BuildTarget.Android; string buildResult = BuildPipeline.BuildPlayer(buildPlayerOptions); } } //if (buildFAT) //{ // for (int i = 0; i < buildFATTextures.Length; i++) // { // if (buildFATTextures[i]) // { // textureConfigsFAT.Add(texturesTarget[i]); // } // } // System.IO.Directory.CreateDirectory(savePath + "/" + AndroidTargetDevice.FAT.ToString()); // for (int j = 0; j < textureConfigsFAT.Count; j++) // { // PlayerSettings.Android.targetDevice = AndroidTargetDevice.FAT; // EditorUserBuildSettings.androidBuildSubtarget = textureConfigsFAT[j]; // BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions(); // PlayerSettings.Android.bundleVersionCode = bundleVersionCode + 30 + j; // string path = savePath + "/" + AndroidTargetDevice.FAT.ToString() + "/" + Application.productName + " - " + PlayerSettings.Android.bundleVersionCode.ToString() + " - " + textureConfigsFAT[j].ToString() + ".apk"; // buildPlayerOptions.scenes = EditorBuildSettingsScene.GetActiveSceneList(EditorBuildSettings.scenes); // buildPlayerOptions.locationPathName = path; // buildPlayerOptions.target = BuildTarget.Android; // string buildResult = BuildPipeline.BuildPlayer(buildPlayerOptions); // } //} }
private static bool IsSceneOpen(EditorBuildSettingsScene scene) { Scene loadedScene = FromBuildSettingsScene(scene); return(loadedScene.isLoaded); }
/// Exports all Sectors in the scene. Safe to call from the command line. public static void ExportSceneChunks() { // Create a progress bar, because we're friendly like that. string progressTitle = "Chunking Level For Streaming"; EditorUtility.DisplayProgressBar(progressTitle, "Preparing", 0); List <EditorBuildSettingsScene> sceneSettings = new List <EditorBuildSettingsScene>(EditorBuildSettings.scenes); EditorBuildSettingsScene rootSceneSettings = new EditorBuildSettingsScene(EditorApplication.currentScene, true); bool sceneExists = false; foreach (EditorBuildSettingsScene oldScene in sceneSettings) { if (oldScene.path == EditorApplication.currentScene) { sceneExists = true; oldScene.enabled = true; break; } } if (!sceneExists) { sceneSettings.Add(rootSceneSettings); EditorBuildSettings.scenes = sceneSettings.ToArray(); } // Export each sector to an individual file. // Inner loop reloads the scene, and Sector creation order is not deterministic, // so it requires multiple passes through the list. int numSectors = SECTR_Sector.All.Count; int progress = 0; int unfrozenSectors = 0; // Figure out how many sectors we should be exporting. for (int sectorIndex = 0; sectorIndex < numSectors; ++sectorIndex) { SECTR_Sector sector = SECTR_Sector.All[sectorIndex]; if (!sector.Frozen) { ++unfrozenSectors; } } while (progress < unfrozenSectors) { for (int sectorIndex = 0; sectorIndex < numSectors; ++sectorIndex) { SECTR_Sector sector = SECTR_Sector.All[sectorIndex]; if (!sector.Frozen) { EditorUtility.DisplayProgressBar(progressTitle, "Exporting " + sector.name, (float)progress / (float)unfrozenSectors); ExportToChunk(sector); ++progress; } } } EditorApplication.SaveScene(); SECTR_VC.WaitForVC(); // Cleanup EditorUtility.ClearProgressBar(); }
void OnGUI() { scrollPos = EditorGUILayout.BeginScrollView(scrollPos); if (GUILayout.Button("Remove PlayerPref", GUILayout.Width(160))) { PlayerPrefs.DeleteAll(); } EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Version:", GUILayout.Width(70)); sversion = EditorGUILayout.TextField(sversion); if (GUILayout.Button("-", GUILayout.Width(20))) { var abc = sversion.Split('.'); if (abc[abc.Length - 1] == "0") { return; } abc[abc.Length - 1] = (int.Parse(abc[abc.Length - 1]) - 1).ToString(); var res = ""; foreach (var r in abc) { if (!string.IsNullOrEmpty(res)) { res += "."; } res += r; } sversion = res; } if (GUILayout.Button("+", GUILayout.Width(20))) { sversion = sversion.Substring(0, sversion.LastIndexOf(".") + 1) + (int.Parse(sversion.Substring(sversion.LastIndexOf(".") + 1)) + 1); } EditorGUILayout.LabelField(" ", GUILayout.Width(20)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("BuildCode:", GUILayout.Width(70)); buildCode = EditorGUILayout.TextField(buildCode); if (GUILayout.Button("-", GUILayout.Width(20))) { var abc = buildCode.Split('.'); if (abc[abc.Length - 1] == "0") { return; } abc[abc.Length - 1] = (int.Parse(abc[abc.Length - 1]) - 1).ToString(); var res = ""; foreach (var r in abc) { if (!string.IsNullOrEmpty(res)) { res += "."; } res += r; } buildCode = res; } if (GUILayout.Button("+", GUILayout.Width(20))) { buildCode = buildCode.Substring(0, buildCode.LastIndexOf(".") + 1) + (int.Parse(buildCode.Substring(buildCode.LastIndexOf(".") + 1)) + 1); } EditorGUILayout.LabelField(" ", GUILayout.Width(20)); EditorGUILayout.EndHorizontal(); EditorGUILayout.LabelField($"Final version:{Application.version}", GUILayout.Width(170)); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Name:", GUILayout.Width(60)); gameName = EditorGUILayout.TextField(gameName); EditorGUILayout.LabelField(" ", GUILayout.Width(20)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("ID:", GUILayout.Width(60)); PlayerSettings.SetApplicationIdentifier(target, EditorGUILayout.TextField(PlayerSettings.applicationIdentifier)); EditorGUILayout.LabelField(" ", GUILayout.Width(20)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); /* * * vrsupport = EditorGUILayout.Toggle("VR Support", vrsupport); * if (vrsupport) * { #if UNITY_2017 * EditorGUILayout.LabelField("└ Supported Devices:" + string.Join(",", UnityEngine.XR.XRSettings.supportedDevices)); #else * EditorGUILayout.LabelField("└ Supported Devices:" + string.Join(",", UnityEngine.XR.XRSettings.supportedDevices)); #endif * } */ EditorGUILayout.Space(); #if UNITY_ANDROID EditorGUILayout.Space(); GUILayout.BeginHorizontal(); EditorGUILayout.LabelField("包地址", GUILayout.Width(50)); targetBuildDir = EditorGUILayout.TextField(targetBuildDir); GUILayout.EndHorizontal(); bUsingIL2CPP = EditorGUILayout.ToggleLeft("是否使用IL2CPP", bUsingIL2CPP); if (GUILayout.Button("Build")) { StartBuild("None"); } #elif UNITY_IOS EditorGUILayout.Space(); GUILayout.BeginHorizontal(); EditorGUILayout.LabelField("包地址", GUILayout.Width(50)); targetBuildDir = EditorGUILayout.TextField(targetBuildDir); GUILayout.EndHorizontal(); bUsingIL2CPP = EditorGUILayout.ToggleLeft("是否使用IL2CPP", bUsingIL2CPP); if (GUILayout.Button("Build")) { QualitySettings.lodBias = 2.4f; StartBuild("None"); } EditorGUILayout.LabelField(" ", GUILayout.Width(20)); #elif UNITY_STANDALONE if (GUILayout.Button("Build")) { StartBuild("PC"); } #endif EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("SourcePath:", GUILayout.Width(100)); assetBundleSourcePath = EditorGUILayout.TextField(assetBundleSourcePath); EditorGUILayout.LabelField(" ", GUILayout.Width(20)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Build AssetBundles", GUILayout.Width(position.width - 200))) { StartBuildAssetBundles(); } if (GUILayout.Button("Clear AssetBundle Names", GUILayout.Width(200))) { ClearAssetBundlesName(); } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); EditorGUILayout.LabelField("From: "+ GetAssetBundleTargetPath()); EditorGUILayout.LabelField("To: " + GetAssetBundleStreamingPath()); if (GUILayout.Button("Copy AssetBundles", GUILayout.Width(position.width - 20))) { CopyDir(GetAssetBundleTargetPath(), GetAssetBundleStreamingPath()); EditorUtility.DisplayDialog("完成", "拷贝完成。", "确定"); AssetDatabase.Refresh(); } EditorGUILayout.Space(); EditorGUILayout.LabelField("相册提示:"); photo = GUILayout.TextArea(photo, GUILayout.Width(position.width - 4)); EditorGUILayout.Space(); EditorGUILayout.LabelField("Build Log:"); sBuildLog = GUILayout.TextArea(sBuildLog, GUILayout.Width(position.width - 4)); EditorGUILayout.Space(); EditorGUILayout.LabelField("场景列表:"); bool bSet = false; GUILayout.BeginHorizontal(); bool bSelectAll = false; if (GUILayout.Button("全选", GUILayout.Width(120))) { bSet = true; bSelectAll = true; } bool bDeselectAll = false; if (GUILayout.Button("全不选", GUILayout.Width(120))) { bSet = true; bDeselectAll = true; } GUILayout.EndHorizontal(); var maps = EditorBuildSettings.scenes; if (containsMaps == null) { containsMaps = new List <string>(); foreach (var m in maps) { if (m.enabled) { if (!containsMaps.Contains(m.path)) { containsMaps.Add(m.path); } } } } foreach (var m in maps) { bool bm = containsMaps.Contains(m.path); bm = EditorGUILayout.ToggleLeft(m.path, bm); if (bm && !containsMaps.Contains(m.path)) { if (!containsMaps.Contains(m.path)) { containsMaps.Add(m.path); } m.enabled = true; bSet = true; break; } else if (!bm && containsMaps.Contains(m.path)) { containsMaps.Remove(m.path); m.enabled = false; bSet = true; break; } } if (bSet) { if (bSelectAll || bDeselectAll) { containsMaps.Clear(); } var amap = new EditorBuildSettingsScene[EditorBuildSettings.scenes.Length]; for (var i = 0; i < EditorBuildSettings.scenes.Length; i++) { var enable = bDeselectAll ? false : (bSelectAll ? true : containsMaps.Contains(EditorBuildSettings.scenes[i].path)); amap[i] = new EditorBuildSettingsScene(EditorBuildSettings.scenes[i].path, enable); if (enable) { containsMaps.Add(EditorBuildSettings.scenes[i].path); } } EditorBuildSettings.scenes = amap; } EditorGUILayout.EndScrollView(); }
protected virtual void ScenesTabGUI() { List <EditorBuildSettingsScene> buildScenes = new List <EditorBuildSettingsScene>(EditorBuildSettings.scenes); this.guids = AssetDatabase.FindAssets("t:Scene"); if (this.selectedScenes == null || this.selectedScenes.Length != guids.Length) { this.selectedScenes = new bool[guids.Length]; } this.scenesTabScrollPosition = EditorGUILayout.BeginScrollView(this.scenesTabScrollPosition); EditorGUILayout.BeginVertical(); if (guids.Length == 0) { GUILayout.Label("No Scenes Found", EditorStyles.centeredGreyMiniLabel); GUILayout.Label("Create New Scenes", EditorStyles.centeredGreyMiniLabel); GUILayout.Label("And Manage them here", EditorStyles.centeredGreyMiniLabel); } for (int i = 0; i < guids.Length; i++) { string path = AssetDatabase.GUIDToAssetPath(guids[i]); SceneAsset sceneAsset = AssetDatabase.LoadAssetAtPath <SceneAsset>(path); EditorBuildSettingsScene buildScene = buildScenes.Find((editorBuildScene) => { return(editorBuildScene.path == path); }); Scene scene = SceneManager.GetSceneByPath(path); bool isOpen = scene.IsValid() && scene.isLoaded; EditorGUILayout.BeginHorizontal(); this.selectedScenes[i] = EditorGUILayout.Toggle(this.selectedScenes[i], GUILayout.Width(15)); if (isOpen) { GUILayout.Label(sceneAsset.name, EditorStyles.whiteLabel); } else { GUILayout.Label(sceneAsset.name, EditorStyles.wordWrappedLabel); } if (this.showPath) { GUILayout.Label(path, EditorStyles.wordWrappedLabel); } if (this.showAddToBuild) { if (GUILayout.Button(buildScene == null ? "+ Build" : "- Build", GUILayout.Width(60))) { if (buildScene == null) { AddToBuild(path); } else { RemoveFromBuild(path); } } } EditorGUI.BeginDisabledGroup(Application.isPlaying); if (GUILayout.Button("Play", GUILayout.Width(50))) { this.lastScene = EditorSceneManager.GetActiveScene().path; Open(path); EditorApplication.isPlaying = true; } EditorGUI.EndDisabledGroup(); if (GUILayout.Button(isOpen ? "Close" : "Open", GUILayout.Width(50))) { if (isOpen) { EditorSceneManager.CloseScene(scene, true); } else { Open(path); } } if (GUILayout.Button("Delete", GUILayout.Width(50))) { Delete(path); } EditorGUILayout.EndHorizontal(); } if (GUILayout.Button("Create New Scene")) { Scene newScene = EditorSceneManager.NewScene(this.newSceneSetup, this.newSceneMode); EditorSceneManager.SaveScene(newScene); } EditorGUILayout.EndVertical(); EditorGUILayout.EndScrollView(); GUILayout.FlexibleSpace(); GUILayout.Label("Bulk Actions", EditorStyles.boldLabel); bool anySelected = false; for (int i = 0; i < this.selectedScenes.Length; i++) { anySelected |= this.selectedScenes[i]; } EditorGUI.BeginDisabledGroup(!anySelected); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Delete")) { for (int i = 0; i < this.selectedScenes.Length; i++) { if (this.selectedScenes[i]) { Delete(AssetDatabase.GUIDToAssetPath(this.guids[i])); } } } if (GUILayout.Button("Open Additive")) { OpenSceneMode openMode = this.openSceneMode; this.openSceneMode = OpenSceneMode.Additive; for (int i = 0; i < this.selectedScenes.Length; i++) { if (this.selectedScenes[i]) { Open(AssetDatabase.GUIDToAssetPath(this.guids[i])); } } this.openSceneMode = openMode; } EditorGUILayout.EndHorizontal(); EditorGUI.EndDisabledGroup(); GUILayout.Label("General Actions", EditorStyles.boldLabel); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Save Modified Scenes")) { EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); } if (GUILayout.Button("Save Open Scenes")) { EditorSceneManager.SaveOpenScenes(); } EditorGUILayout.EndHorizontal(); }
protected void DoPreprocessBuild(BuildTarget target, string path) { BuildTargetGroup buildTargetGroup; if (target == BuildTarget.Android) { buildTargetGroup = BuildTargetGroup.Android; } else if (target == BuildTarget.iOS) { buildTargetGroup = BuildTargetGroup.iOS; } else { return; } EditorBuildSettingsScene enabledBuildScene = null; int enabledSceneCount = 0; foreach (var buildScene in EditorBuildSettings.scenes) { if (!buildScene.enabled) { continue; } enabledBuildScene = buildScene; enabledSceneCount++; } if (enabledSceneCount != 1) { return; } List <Texture2D> exampleSceneIcons = new List <Texture2D>(); List <string> exampleProductNames = new List <string>(); foreach (var exampleScene in _exampleScenes) { exampleSceneIcons.Add(AssetDatabase.LoadAssetAtPath <Texture2D>( AssetDatabase.GUIDToAssetPath(exampleScene.IconGuid))); exampleProductNames.Add(exampleScene.ProductName); } string[] projectFolders = Application.dataPath.Split('/'); string defaultProductName = projectFolders[projectFolders.Length - 2]; if (PlayerSettings.productName != defaultProductName && !exampleProductNames.Contains(PlayerSettings.productName)) { return; } Texture2D[] applicationIcons = PlayerSettings.GetIconsForTargetGroup(buildTargetGroup, IconKind.Application); for (int i = 0; i < applicationIcons.Length; i++) { if (applicationIcons[i] != null && !exampleSceneIcons.Contains(applicationIcons[i])) { return; } } foreach (var exampleScene in _exampleScenes) { if (enabledBuildScene.guid.ToString() == exampleScene.SceneGuid) { PlayerSettings.productName = exampleScene.ProductName; Texture2D exampleIcon = AssetDatabase.LoadAssetAtPath <Texture2D>( AssetDatabase.GUIDToAssetPath(exampleScene.IconGuid)); for (int i = 0; i < applicationIcons.Length; i++) { applicationIcons[i] = exampleIcon; } PlayerSettings.SetIconsForTargetGroup( buildTargetGroup, applicationIcons, IconKind.Application); break; } } }
public static string SceneFileName(EditorBuildSettingsScene scene) { return(SceneFileName(scene.path)); }
private void OnGUI() { gameName = EditorGUILayout.TextField("Name of your Game: ", gameName); if (GUILayout.Button("Add Game")) { //create folder to put new game files in string path = "Assets/Games/" + gameName; string guid = AssetDatabase.CreateFolder("Assets/Games", gameName); string newFolderPath = AssetDatabase.GUIDToAssetPath(guid); //create menu for game from template Scene newMenuScene; SceneTemplateAsset sceneTemplate = (SceneTemplateAsset)AssetDatabase.LoadAssetAtPath("Assets/General Assets/Scenes/Templates/MenuTemplate.scenetemplate", typeof(SceneTemplateAsset)); if (sceneTemplate == null) { Debug.Log("menu template not found"); return; } else { newMenuScene = SceneTemplateService.Instantiate(sceneTemplate, true, "Assets/Games/MainMenus/" + gameName + "~Menu.unity").scene; } //create menu for game from template Scene newHighScoreScene; SceneTemplateAsset sceneTemplateHighscore = (SceneTemplateAsset)AssetDatabase.LoadAssetAtPath("Assets/General Assets/Scenes/Templates/HighscoreTemplate.scenetemplate", typeof(SceneTemplateAsset)); if (sceneTemplateHighscore == null) { Debug.Log("highscore template not found"); return; } else { newHighScoreScene = SceneTemplateService.Instantiate(sceneTemplateHighscore, true, "Assets/Games/Highscores/" + gameName + "Highscores.unity").scene; } GameObject.Find("PlayButton"); //create scene for actual game var newGameScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Additive); newGameScene.name = gameName; EditorSceneManager.SaveScene(newGameScene, path + "/" + gameName + ".unity"); Debug.Log(newGameScene.path); //add new scenes to build settings string[] ScenesList = new string[] { newMenuScene.path, newHighScoreScene.path, newGameScene.path }; EditorBuildSettingsScene[] original = EditorBuildSettings.scenes; EditorBuildSettingsScene[] newSettings = new EditorBuildSettingsScene[original.Length + ScenesList.Length]; System.Array.Copy(original, newSettings, original.Length); int index = original.Length; for (int i = 0; i < ScenesList.Length; i++) { EditorBuildSettingsScene sceneToAdd = new EditorBuildSettingsScene(ScenesList[i], true); newSettings[index] = sceneToAdd; index++; } EditorBuildSettings.scenes = newSettings; AssetDatabase.SaveAssets(); Debug.Log("Game successfully added"); Close(); } }
internal EbsSceneState(EditorBuildSettingsScene s) { guid = s.guid.ToString(); enabled = s.enabled; }
// シーンを Editor の設定から取り出す static string[] GetScenes() { return(EditorBuildSettingsScene.GetActiveSceneList(EditorBuildSettings.scenes)); }
static void buildSpecificPlayer(BuildTarget buildTarget) { // Get filename. string path = EditorUtility.SaveFolderPanel("Choose Location of Built Game", "", ""); if (path != string.Empty) { List <string> levels = new List <string>(EditorBuildSettings.scenes.Length); for (int i = 0; i < EditorBuildSettings.scenes.Length; ++i) { EditorBuildSettingsScene scene = EditorBuildSettings.scenes[i]; if (scene.enabled) { levels.Add(scene.path); UnityEngine.Debug.Log(scene); } } // Build player. var report = BuildPipeline.BuildPlayer(levels.ToArray(), path + "/" + applicationName + ".exe", buildTarget, BuildOptions.None); if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded) { return; } if (Directory.Exists("Assets/Custom Resources")) { // Copy a file from the project folder to the build folder, alongside the built game. clearAndDeleteDirectory(path + "/Custom Resources"); FileUtil.CopyFileOrDirectory("Assets/Custom Resources", path + "/Custom Resources"); } if (Directory.Exists("Assets/Documentation")) { // Copy a file from the project folder to the build folder, alongside the built game. clearAndDeleteDirectory(path + "/Documentation"); FileUtil.CopyFileOrDirectory("Assets/Documentation", path + "/Documentation"); } if (Directory.Exists("Assets\\ExtraBuildFiles")) { // Copy a file from the project folder to the build folder, alongside the built game. foreach (string filepath in Directory.GetFiles("Assets\\ExtraBuildFiles")) { FileUtil.CopyFileOrDirectory(filepath, path + "/" + Path.GetFileName(filepath)); } } foreach (string file in Directory.GetFiles(path, "*.meta", SearchOption.AllDirectories)) { File.Delete(file); } #if HACKY_PLUGIN_FIX string dataPath = path + "/" + applicationName + "_Data/"; string destFolder = dataPath + "Mono/"; if (copyToMonoFiles.Length > 0) { Directory.CreateDirectory(destFolder); // Make sure this exists } foreach (string file in copyToMonoFiles) { string pluginPath = dataPath + "Plugins/" + file; if (File.Exists(pluginPath)) { string dest = destFolder + file; File.Copy(pluginPath, dest); } } #endif } else { UnityEngine.Debug.Log("Build canceled"); } }
public static GUIContent SceneGUIContent(EditorBuildSettingsScene scene) { return(SceneGUIContent(scene.path)); }
static void BuildSceneMenu() { var selectedObjects = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets); if (selectedObjects != null && selectedObjects.Length == 1) { string[] scenes = new string[1]; scenes[0] = AssetDatabase.GetAssetOrScenePath(selectedObjects[0]); if (!scenes[0].Contains(".unity")) { Debug.LogWarning("You did not choose a scene file to buid"); return; } string path; string ext = ""; switch (EditorUserBuildSettings.activeBuildTarget) { case BuildTarget.Android: ext = "apk"; break; case BuildTarget.StandaloneWindows: ext = "exe"; break; case BuildTarget.StandaloneOSX: ext = "app"; break; default: break; } if (EditorPrefs.HasKey(scenes[0])) { path = EditorPrefs.GetString(scenes[0]); } else { path = Application.dataPath; } path = EditorUtility.SaveFilePanel("Build file", Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + "." + ext, ext); if (!string.IsNullOrEmpty(path)) { EditorPrefs.SetString(scenes[0], Path.GetFullPath(path)); if (EditorBuildSettings.scenes.Length > 0) { var first = EditorBuildSettings.scenes[0]; var newone = new EditorBuildSettingsScene(path, true); EditorBuildSettings.scenes[0] = newone; BuildPipeline.BuildPlayer(scenes, path, EditorUserBuildSettings.activeBuildTarget, BuildOptions.ShowBuiltPlayer); EditorBuildSettings.scenes[0] = first; } else { var tempScenes = new EditorBuildSettingsScene[1]; var newone = new EditorBuildSettingsScene(path, true); tempScenes[0] = newone; EditorBuildSettings.scenes = tempScenes; BuildPipeline.BuildPlayer(scenes, path, EditorUserBuildSettings.activeBuildTarget, BuildOptions.ShowBuiltPlayer); EditorBuildSettings.scenes = null; } } } }
static void ExportItemMap() { List <MapInfo> maps = new List <MapInfo>(); for (int idx = 0; idx < EditorBuildSettings.scenes.Length; idx++) { EditorBuildSettingsScene s = EditorBuildSettings.scenes[idx]; if (s.enabled) { //EditorSceneManager.OpenScene(s.path); MapInfo mapInfo = new MapInfo(); mapInfo.Id = idx; if (null != mapInfo.ItemMapInfo) { mapInfo.ItemMapInfo.Clear(); } else { mapInfo.ItemMapInfo = new List <ItemMapInfo>(); } GameObject[] items = GameObject.FindGameObjectsWithTag("Item"); if (items.Length > 0) { foreach (GameObject go in items) { Transform t = go.transform; MapArea area = MapArea.NONE; DropMapArea a = t.parent.GetComponent <DropMapArea>(); if (null != a) { area = a.mapArea; } Vector3 v = t.position; float w = t.localScale.x; float h = t.localScale.z; ItemMapInfo m = new ItemMapInfo(ItemMapType.ITEM, area, v.x, v.z, w, h); mapInfo.ItemMapInfo.Add(m); } } GameObject[] points = GameObject.FindGameObjectsWithTag("Point"); if (points.Length > 0) { foreach (GameObject go in items) { Transform t = go.transform; MapArea area = MapArea.NONE; DropMapArea a = t.parent.GetComponent <DropMapArea>(); if (null != a) { area = a.mapArea; } Vector3 v = t.position; float w = t.localScale.x; float h = t.localScale.z; ItemMapInfo m = new ItemMapInfo(ItemMapType.POINT, area, v.x, v.z, w, h); mapInfo.ItemMapInfo.Add(m); } } maps.Add(mapInfo); } } Util.Serialize <List <MapInfo> >(maps, AppConst.AppStreamingPath + "/" + AppConst.TextDir + "/map.bin"); AssetDatabase.Refresh(); }
private void DrawScenes() { EditorGUILayout.LabelField("Scenes in Build", EditorStyles.boldLabel); //EditorGUI.indentLevel++; var style = new GUIStyle(GUI.skin.box); style.stretchHeight = true; _scenesScrollBarPosition = EditorGUILayout.BeginScrollView(_scenesScrollBarPosition, style); bool changed = false; var scenes = EditorBuildSettings.scenes; for (int i = 0; i < scenes.Length; i++) { var r = EditorGUILayout.GetControlRect(); var r0 = new Rect(r.xMin, r.yMin, 25f, r.height); var r1 = new Rect(r0.xMax, r.yMin, (r.xMax - r0.xMax) * 0.66f, r.height); var r2 = new Rect(r1.xMax, r.yMin, r.xMax - r1.xMax, r.height); EditorGUI.BeginChangeCheck(); scenes[i].enabled = EditorGUI.Toggle(r0, scenes[i].enabled); if (EditorGUI.EndChangeCheck()) { changed = true; } EditorGUI.LabelField(r1, EditorHelper.TempContent(scenes[i].path)); var scene = AssetDatabase.LoadAssetAtPath <SceneAsset>(scenes[i].path); EditorGUI.BeginChangeCheck(); scene = EditorGUI.ObjectField(r2, GUIContent.none, scene, typeof(SceneAsset), false) as SceneAsset; if (EditorGUI.EndChangeCheck()) { changed = true; scenes[i] = new EditorBuildSettingsScene(AssetDatabase.GetAssetPath(scene), scenes[i].enabled); } } if (changed) { EditorBuildSettings.scenes = scenes; } EditorGUILayout.EndScrollView(); //DRAG & DROP ON SCROLLVIEW var dropArea = GUILayoutUtility.GetLastRect(); var ev = Event.current; switch (ev.type) { case EventType.DragUpdated: if (dropArea.Contains(ev.mousePosition) && (from o in DragAndDrop.objectReferences where o is SceneAsset select o).Any()) { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; } break; case EventType.DragPerform: if (dropArea.Contains(ev.mousePosition) && (from o in DragAndDrop.objectReferences where o is SceneAsset select o).Any()) { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; DragAndDrop.AcceptDrag(); var lst = new List <EditorBuildSettingsScene>(EditorBuildSettings.scenes); foreach (var o in DragAndDrop.objectReferences) { var scene = o as SceneAsset; if (scene == null) { continue; } var p = AssetDatabase.GetAssetPath(scene); if (!(from s in lst where s.path == p select s).Any()) { lst.Add(new EditorBuildSettingsScene(p, true)); } } EditorBuildSettings.scenes = lst.ToArray(); } break; } //////////////// //BUTTONS! var rect = EditorGUILayout.GetControlRect(); //DESELECT var selectAllPosition = new Rect(rect.xMin, rect.yMin, 100f, rect.height); if (GUI.Button(selectAllPosition, new GUIContent("Select All"))) { var arr = EditorBuildSettings.scenes; foreach (var s in arr) { s.enabled = true; } EditorBuildSettings.scenes = arr; } //DESELECT var deselectPosition = new Rect(rect.xMin + 105f, rect.yMin, 100f, rect.height); if (GUI.Button(deselectPosition, new GUIContent("Deselect All"))) { var arr = EditorBuildSettings.scenes; foreach (var s in arr) { s.enabled = false; } EditorBuildSettings.scenes = arr; } //CLEAR var cancelPosition = new Rect(rect.xMax - 110f, rect.yMin, 50f, rect.height); if (GUI.Button(cancelPosition, new GUIContent("Clear"))) { EditorBuildSettings.scenes = new EditorBuildSettingsScene[] { }; } //SYNC var applyPosition = new Rect(rect.xMax - 55f, rect.yMin, 50f, rect.height); var oldScenes = EditorBuildSettings.scenes; if (GUI.Button(applyPosition, new GUIContent("Add All"))) { var lst = new List <EditorBuildSettingsScene>(); var mainFolder = Application.dataPath.EnsureNotEndsWith("Assets"); foreach (var file in Directory.GetFiles(Application.dataPath + "/Scenes", "*.unity", SearchOption.AllDirectories)) { var normalizedFile = file.EnsureNotStartWith(mainFolder); bool enabled = (from s in oldScenes where s.enabled && s.path == normalizedFile select s).Any(); lst.Add(new EditorBuildSettingsScene(normalizedFile, enabled)); } EditorBuildSettings.scenes = lst.ToArray(); } //EditorGUI.indentLevel--; }
static string BuildAndroidPackage(string channelId, string subChannelId = "", string postfix = ".apk") { BuildAndroid.PreProcessDigitalSignature(); //@{{ CAUTION!! // // delete the other SDK alipay_msp.jar to avoid conflict with the one in gfansdk_pay.jar // string alipayFile; string backupAlipay; if (channelId.StartsWith(PlatformGfan)) { alipayFile = Application.dataPath + "/Plugins/Android/libs/alipay_msp.jar"; backupAlipay = Application.dataPath + "/alipay_msp.jar"; } else { alipayFile = Application.dataPath + "/Plugins/Android/libs/gfansdk_pay.jar"; backupAlipay = Application.dataPath + "/gfansdk_pay.jar"; } if (File.Exists(alipayFile)) { if (File.Exists(backupAlipay)) { File.Delete(backupAlipay); } File.Move(alipayFile, backupAlipay); } else { throw new System.Exception("Failed!! Please Update SVN to restore : " + alipayFile); } //@}} // Prepare all levels List <string> levels = new List <string>(); EditorBuildSettingsScene scene = null; for (int i = 0; i < EditorBuildSettings.scenes.Length; i++) { scene = EditorBuildSettings.scenes[i]; if (scene.enabled) { levels.Add(scene.path); } } string path = BuildAndroid.GetCombineApkName(channelId, subChannelId, postfix); BuildPipeline.BuildPlayer(levels.ToArray(), path, BuildTarget.Android, BuildOptions.None); //@{{ CAUTION!! // // copy back // if (!File.Exists(alipayFile)) { if (File.Exists(backupAlipay)) { File.Move(backupAlipay, alipayFile); } else { throw new System.Exception("Failed!! Please Update SVN to restore : " + alipayFile); } } //@}} return(path); }
/// <summary> /// あらゆる種類の任意の数のアセットがインポートが完了したときに呼ばれる処理です。 /// </summary> /// <param name="importedAssets"> インポートされたアセットのファイルパス。 </param> /// <param name="deletedAssets"> 削除されたアセットのファイルパス。 </param> /// <param name="movedAssets"> 移動されたアセットのファイルパス。 </param> /// <param name="movedFromPath"> 移動されたアセットの移動前のファイルパス。 </param> static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath) { var editorConfig = ProjectFolders.Instance; var sceneImporterConfig = SceneImporterConfig.Instance; if (sceneImporterConfig == null) { return; } var sceneFileExtension = SceneImporterConfig.SceneFileExtension; // ビルドセッティングファイルの更新時. if (importedAssets.Any(x => Path.GetFileName(x) == BuildSettingsFileName)) { var buildTargetScenes = EditorBuildSettings.scenes; var sceneCount = buildTargetScenes.Length; var scenes = buildTargetScenes .Where(x => x != null) .Where(x => !string.IsNullOrEmpty(x.path)) .DistinctBy(x => x.path) .ToArray(); if (scenes.Length != sceneCount) { EditorBuildSettings.scenes = scenes; ScenesScriptGenerator.Generate(sceneImporterConfig.ManagedFolders, editorConfig.ConstantsScriptPath); AssetDatabase.SaveAssets(); Debug.Log("Update BuildSettings asset."); } } var assetPaths = new[] { importedAssets, deletedAssets, movedFromPath, movedAssets }.SelectMany(x => x); if (assetPaths.Any(x => Path.GetExtension(x) == sceneFileExtension)) { var isChanged = false; var autoAdditionFolders = sceneImporterConfig.ManagedFolders; var buildTargetScenes = EditorBuildSettings.scenes.ToDictionary(x => x.path); //-------------------------------------------------------------------- // 移動 (ビルド対象から外れる場合). //-------------------------------------------------------------------- for (var i = 0; i < movedAssets.Length; ++i) { if (!buildTargetScenes.ContainsKey(movedAssets[i])) { continue; } // ビルド対象フォルダ内の移動は除外処理しない. if (autoAdditionFolders.Any(y => movedAssets[i].StartsWith(y))) { continue; } // ビルドターゲットに入っているシーンが移動した場合ビルド対象から外す. buildTargetScenes.Remove(movedAssets[i]); isChanged = true; } //-------------------------------------------------------------------- // 移動 (ビルド対象に追加される場合.). //-------------------------------------------------------------------- // .unity かつ、自動追加対象フォルダ以下のファイルパスを取得. var movedInScenes = movedAssets .Where(x => Path.GetExtension(x) == sceneFileExtension) .Where(x => autoAdditionFolders.Any(y => x.StartsWith(y))); foreach (var movedInScene in movedInScenes) { if (buildTargetScenes.ContainsKey(movedInScene)) { continue; } // buildTargetScenesに入っていない物を追加. buildTargetScenes[movedInScene] = new EditorBuildSettingsScene(movedInScene, true); isChanged = true; } //-------------------------------------------------------------------- // リネーム. //-------------------------------------------------------------------- for (var i = 0; i < movedAssets.Length; ++i) { if (!buildTargetScenes.ContainsKey(movedAssets[i])) { continue; } // 別ディレクトリなら「ファイル移動」なので処理しない. if (Path.GetDirectoryName(movedAssets[i]) != Path.GetDirectoryName(movedFromPath[i])) { continue; } if (Path.GetFileName(movedAssets[i]) != Path.GetFileName(movedFromPath[i])) { isChanged = true; } } //-------------------------------------------------------------------- // 削除. //-------------------------------------------------------------------- foreach (var deletedAsset in deletedAssets) { if (!buildTargetScenes.ContainsKey(deletedAsset)) { continue; } // ビルドターゲットに入っているシーンが消されたらビルド対象から外す. buildTargetScenes.Remove(deletedAsset); isChanged = true; } //-------------------------------------------------------------------- // 追加. //-------------------------------------------------------------------- // .unity かつ、自動追加対象フォルダ以下のファイルパスを取得. var addScenes = importedAssets .Where(x => Path.GetExtension(x) == sceneFileExtension) .Where(x => autoAdditionFolders.Any(y => x.StartsWith(y))); foreach (var addScene in addScenes) { if (buildTargetScenes.ContainsKey(addScene)) { continue; } // buildTargetScenesに入っていない物を追加. buildTargetScenes[addScene] = new EditorBuildSettingsScene(addScene, true); isChanged = true; } if (isChanged) { ScenesInBuildGenerator.UpdateBuildTargetScenes(sceneImporterConfig, editorConfig.ConstantsScriptPath, buildTargetScenes); } } }
internal void OnGUI() { GUIStyle buttonStyle = new GUIStyle(GUI.skin.GetStyle("Button")) { alignment = TextAnchor.MiddleLeft }; EditorGUILayout.BeginVertical(); this.scrollPos = EditorGUILayout.BeginScrollView(this.scrollPos, false, false); GUILayout.Space(10); GUIStyle favoritesFoldoutStyle = new GUIStyle(EditorStyles.foldout); favoritesFoldoutStyle.fontStyle = FontStyle.Bold; showFavorites = EditorGUILayout.Foldout(showFavorites, "Favorites", true, favoritesFoldoutStyle); if (showFavorites) { for (int i = 0; i < favorites.scenes.Count; i++) { string assetPath = AssetDatabase.GUIDToAssetPath(favorites.scenes[i]); if (assetPath != null && assetPath != "") { string sceneName = Path.GetFileNameWithoutExtension(assetPath); EditorGUILayout.BeginHorizontal(); bool favorite = GUILayout.Button(EditorGUIUtility.IconContent("Favorite"), EditorStyles.boldLabel, GUILayout.ExpandWidth(false)); bool pressed = GUILayout.Button(string.Format("{0}", sceneName), buttonStyle); EditorGUILayout.EndHorizontal(); //If favorite button was clicked if (favorite) { ToggleFavorite(favorites.scenes[i]); } //If button was pressed if (pressed) { OpenScene(assetPath); } } } } GUILayout.Space(10); showBuildScenes = EditorGUILayout.Foldout(showBuildScenes, "Scenes In Build", true); if (showBuildScenes) { for (int i = 0; i < EditorBuildSettings.scenes.Length; i++) { EditorBuildSettingsScene scene = EditorBuildSettings.scenes[i]; if (scene.path != null && scene.path != "") { string sceneName = Path.GetFileNameWithoutExtension(scene.path); EditorGUILayout.BeginHorizontal(); bool isFavorite = favorites.scenes.Contains(scene.guid.ToString()); bool favorite = GUILayout.Button(EditorGUIUtility.IconContent(isFavorite ? "Favorite" : "d_favorite"), EditorStyles.boldLabel, GUILayout.ExpandWidth(false)); bool pressed = GUILayout.Button(string.Format("{0}", sceneName), buttonStyle); if (favorite) { ToggleFavorite(scene.guid.ToString()); } EditorGUILayout.EndHorizontal(); //If button was pressed if (pressed) { OpenScene(scene.path); } } } } GUILayout.Space(10); showAllScenes = EditorGUILayout.Foldout(showAllScenes, "All Scenes", true); if (showAllScenes) { string[] guids = AssetDatabase.FindAssets("t:Scene"); for (int i = 0; i < guids.Length; i++) { string scenePath = AssetDatabase.GUIDToAssetPath(guids[i]); string sceneName = Path.GetFileNameWithoutExtension(scenePath); EditorGUILayout.BeginHorizontal(); bool isFavorite = favorites.scenes.Contains(guids[i]); bool favorite = GUILayout.Button(EditorGUIUtility.IconContent(isFavorite ? "Favorite" : "d_favorite"), EditorStyles.boldLabel, GUILayout.ExpandWidth(false)); bool pressed = GUILayout.Button(string.Format("{0}", sceneName), buttonStyle); EditorGUILayout.EndHorizontal(); //If favorite button was clicked if (favorite) { ToggleFavorite(guids[i]); } if (pressed) { OpenScene(scenePath); } } } GUILayout.Space(10); EditorGUILayout.EndScrollView(); EditorGUILayout.EndVertical(); }
public EBSSceneState(EditorBuildSettingsScene s) { guid = s.guid.ToString(); enabled = s.enabled; }
/// Exports the specific Sector into an external level file, deleting the current scene copy in the process. Safe to call from command line. /// <param name="sector">The Sector to export.</param> /// <returns>Returns true if Sector was successfully exported, false otherwise.</returns> public static bool ExportToChunk(SECTR_Sector sector) { if (string.IsNullOrEmpty(EditorApplication.currentScene)) { Debug.LogError("Scene must be saved befor export."); return(false); } if (sector == null) { Debug.LogError("Cannot export null Sector."); return(false); } if (!sector.gameObject.activeInHierarchy) { Debug.LogError("Cannot export inactive Sectors."); return(false); } if (!sector.gameObject.isStatic) { Debug.Log("Skipping export of dynamic sector" + sector.name + "."); return(true); } if (sector.Frozen) { // Already exported Debug.Log("Skipping frozen sector " + sector.name); return(true); } string sceneDir; string sceneName; string exportDir = SECTR_Asset.MakeExportFolder("Chunks", false, out sceneDir, out sceneName); if (string.IsNullOrEmpty(exportDir)) { Debug.LogError("Could not create Chunks folder."); return(false); } // Delete the previous export, if there is one. // Prevents duplicate names piling up. SECTR_Chunk oldChunk = sector.GetComponent <SECTR_Chunk>(); if (oldChunk) { AssetDatabase.DeleteAsset(oldChunk.NodeName); SECTR_VC.WaitForVC(); } // Sectors are not guaranteed to be uniquely named, so always generate a unique name. string originalSectorName = sector.name; string newAssetPath = AssetDatabase.GenerateUniqueAssetPath(exportDir + sceneName + "_" + originalSectorName + ".unity"); sector.name = newAssetPath; // Make sure the current scene is saved, preserving all changes. EditorApplication.SaveScene(); SECTR_VC.WaitForVC(); string originalScene = EditorApplication.currentScene; List <EditorBuildSettingsScene> sceneSettings = new List <EditorBuildSettingsScene>(EditorBuildSettings.scenes); // SaveScene can cause crashes w/ version control, so we work around it with a copy. AssetDatabase.CopyAsset(originalScene, newAssetPath); SECTR_VC.WaitForVC(); EditorApplication.OpenScene(newAssetPath); SECTR_VC.WaitForVC(); sector = _FindSectorByName(newAssetPath); // Make sure to force update all members so that membership info is correct. List <SECTR_Member> allMembers = FindAllOfType <SECTR_Member>(); for (int memberIndex = 0; memberIndex < allMembers.Count; ++memberIndex) { allMembers[memberIndex].ForceUpdate(true); } // Multi-sector members need to stay in the master scene. foreach (SECTR_Member member in allMembers) { if (member.Sectors.Count > 1 && member.transform.IsChildOf(sector.transform)) { bool unparentMember = true; // Only affect the first member in the hierarchy below the sector Transform parent = member.transform.parent; while (parent != sector.transform) { if (parent.GetComponent <SECTR_Member>() != null) { unparentMember = false; break; } parent = parent.parent; } if (unparentMember) { if (PrefabUtility.GetPrefabType(sector.gameObject) != PrefabType.None) { Debug.LogWarning("Export is unparenting shared member " + member.name + " from prefab Sector " + sector.name + ". This will break the prefab."); } member.transform.parent = null; } } } // Unparent the sector from anything sector.transform.parent = null; // Any children of this sector should be exported. // The rest should be destroyed. List <Transform> allXforms = FindAllOfType <Transform>(); #if !UNITY_STREAM_ENLIGHTEN List <int> referencedLightmaps = new List <int>(LightmapSettings.lightmaps.Length); #endif foreach (Transform transform in allXforms) { if (transform && transform.IsChildOf(sector.transform)) { #if !UNITY_STREAM_ENLIGHTEN Renderer childRenderer = transform.GetComponent <Renderer>(); if (childRenderer && childRenderer.lightmapIndex >= 0 && !referencedLightmaps.Contains(childRenderer.lightmapIndex)) { referencedLightmaps.Add(childRenderer.lightmapIndex); } Terrain childTerrain = transform.GetComponent <Terrain>();; if (childTerrain && childTerrain.lightmapIndex >= 0 && !referencedLightmaps.Contains(childTerrain.lightmapIndex)) { referencedLightmaps.Add(childTerrain.lightmapIndex); } #endif } else if (transform) { GameObject.DestroyImmediate(transform.gameObject); } } #if !UNITY_STREAM_ENLIGHTEN if (referencedLightmaps.Count > 0) { SECTR_LightmapRef newRef = sector.GetComponent <SECTR_LightmapRef>(); if (!newRef) { newRef = sector.gameObject.AddComponent <SECTR_LightmapRef>(); } newRef.ReferenceLightmaps(referencedLightmaps); } // Nuke global data like nav meshes and lightmaps // Lightmap indexes will be preserved on export. NavMeshBuilder.ClearAllNavMeshes(); #if !UNITY_4 SerializedObject serialObj = new SerializedObject(GameObject.FindObjectOfType <LightmapSettings>()); SerializedProperty snapshotProp = serialObj.FindProperty("m_LightmapSnapshot"); snapshotProp.objectReferenceValue = null; serialObj.ApplyModifiedProperties(); #endif LightmapSettings.lightmaps = new LightmapData[0]; LightmapSettings.lightProbes = new LightProbes(); #endif GameObject dummyParent = new GameObject(newAssetPath); SECTR_ChunkRef chunkRef = dummyParent.AddComponent <SECTR_ChunkRef>(); chunkRef.RealSector = sector.transform; sector.transform.parent = dummyParent.transform; // If the sector has a chunk marked for re-use, perform some special work. SECTR_Chunk originalChunk = sector.GetComponent <SECTR_Chunk>(); if (originalChunk && originalChunk.ExportForReuse) { chunkRef.Recentered = true; sector.transform.localPosition = Vector3.zero; sector.transform.localRotation = Quaternion.identity; sector.transform.localScale = Vector3.one; sector.gameObject.SetActive(false); } // Rename the real chunk root with a clear name. sector.name = originalSectorName + "_Chunk"; // Strip off any functional objects that will be preserved in the root scene. // Destroy the chunk first because it has dependencies on Sector. GameObject.DestroyImmediate(originalChunk); Component[] components = sector.GetComponents <Component>(); foreach (Component component in components) { if (component.GetType().IsSubclassOf(typeof(MonoBehaviour)) && component.GetType() != typeof(Terrain) && component.GetType() != typeof(SECTR_LightmapRef)) { GameObject.DestroyImmediate(component); } } // Re-add a member that will persist all of the references and save us work post load. SECTR_Member refMember = chunkRef.RealSector.gameObject.AddComponent <SECTR_Member>(); refMember.NeverJoin = true; refMember.BoundsUpdateMode = SECTR_Member.BoundsUpdateModes.Static; refMember.ForceUpdate(true); // Save scene and append it to the build settings. EditorApplication.SaveScene(); SECTR_VC.WaitForVC(); EditorBuildSettingsScene sectorSceneSettings = new EditorBuildSettingsScene(newAssetPath, true); bool sceneExists = false; foreach (EditorBuildSettingsScene oldScene in sceneSettings) { if (oldScene.path == newAssetPath) { sceneExists = true; oldScene.enabled = true; break; } } if (!sceneExists) { sceneSettings.Add(sectorSceneSettings); } string[] pathParts = newAssetPath.Split('/'); string sectorPath = pathParts[pathParts.Length - 1].Replace(".unity", ""); // Update the master scene with exported info. EditorApplication.OpenScene(originalScene); SECTR_VC.WaitForVC(); sector = _FindSectorByName(newAssetPath); sector.name = originalSectorName; DeleteExportedSector(sector); // Make sure Sectors has a Chunk SECTR_Chunk newChunk = sector.GetComponent <SECTR_Chunk>(); if (!newChunk) { newChunk = sector.gameObject.AddComponent <SECTR_Chunk>(); } newChunk.ScenePath = sectorPath; newChunk.NodeName = newAssetPath; newChunk.enabled = true; // Disable a TerrainComposer node if there is one. MonoBehaviour terrainNeighbors = sector.GetComponent("TerrainNeighbors") as MonoBehaviour; if (terrainNeighbors) { terrainNeighbors.enabled = false; } // Save off the accumulated build settings EditorBuildSettings.scenes = sceneSettings.ToArray(); AssetDatabase.Refresh(); EditorApplication.SaveScene(); SECTR_VC.WaitForVC(); return(true); }
void DrawSceneButton(EditorBuildSettingsScene scene, bool isActiveScene, Color defColor, out bool nowClicked) { nowClicked = false; #region get sceneName(path) string sceneName = ""; switch (viewOption) { case 0: //Show full path (remove "ASSETS/") sceneName = scene.path.Remove(0, 7); break; case 1: //Show only scene name sceneName = System.IO.Path.GetFileName(scene.path); break; } #endregion #region draw scene text bool isNowSelectedScene = (selectedSceneIndex == nowSceneIndex); GUIContent sceneText = new GUIContent(sceneName); Rect sceneTextRect = GUILayoutUtility.GetRect(sceneText, sceneTextStyle); //Draw background when selected if (isNowSelectedScene) { if (focusedWindow == this) { GUI.color = EditorGUIUtility.isProSkin ? (scene.enabled ? proSelectBackground : proDisableSelectBackground) : (scene.enabled ? stdSelectBackground : stdDisableSelectBackground); } else { GUI.color = EditorGUIUtility.isProSkin ? (scene.enabled ? proLostFocusSelectBackground : proLostFocusDisableSelectBackground) : (scene.enabled ? stdLostFocusSelectBackground : stdLostFocusDisableSelectBackground); } GUI.DrawTexture(sceneTextRect, EditorGUIUtility.whiteTexture); } GUI.color = scene.enabled ? (EditorGUIUtility.isProSkin ? proTextColor : (isNowSelectedScene ? stdSelectTextColor : stdTextColor)) : (EditorGUIUtility.isProSkin ? proDisableTextColor : (isNowSelectedScene ? stdSelectDisableTextColor : stdDisableTextColor)); GUIStyle nowSceneTextStyle = isNowSelectedScene ? sceneSelectedTextStyle : sceneTextStyle; nowSceneTextStyle.fontStyle = isActiveScene ? FontStyle.Bold : FontStyle.Normal; GUI.Label(sceneTextRect, sceneText, nowSceneTextStyle); #endregion #region when click Event e = Event.current; if (sceneTextRect.Contains(e.mousePosition)) { if (e.type == EventType.MouseDown) { nowClicked = true; selectedSceneIndex = nowSceneIndex; } else if (e.type == EventType.MouseUp) { if (e.button == 0) { if (lastClickedScene == nowSceneIndex && Time.realtimeSinceStartup - lastClickTime <= DoubleClickDelay) { SceneMenuCallback(new object[] { scene, SceneMenuType.Open }); } else { lastClickedScene = nowSceneIndex; lastClickTime = Time.realtimeSinceStartup; } } else if (e.button == 1) { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("Show in Project"), false, SceneMenuCallback, new object[] { scene, SceneMenuType.ShowInProject }); menu.AddItem(new GUIContent("Show in Explorer"), false, SceneMenuCallback, new object[] { scene, SceneMenuType.ShowInExplorer }); menu.AddSeparator(""); menu.AddItem(new GUIContent("Open"), false, SceneMenuCallback, new object[] { scene, SceneMenuType.Open }); menu.AddItem(new GUIContent("Open Scene Addtive"), false, SceneMenuCallback, new object[] { scene, SceneMenuType.ShowInAddtive }); menu.ShowAsContext(); } } } #endregion nowSceneIndex++; GUI.color = defColor; }
void OnGUI() { GUIStyle style = new GUIStyle(); style.fontSize = 18; var color = GUI.backgroundColor; using (var v = new EditorGUILayout.VerticalScope(GUI.skin.box)) { GUILayout.Space(5); using (var vv = new EditorGUILayout.VerticalScope(GUI.skin.box)) { EditorGUILayout.LabelField("打包", style); GUILayout.Space(5); using (var h = new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("选择目标平台:", style); GUILayout.Space(15); _platform = (BuildPlatform)EditorGUILayout.EnumPopup(_platform); } GUILayout.Space(5); using (var h = new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("打包选项:", style); GUILayout.Space(15); _buildOptions = (BuildOptions)EditorGUILayout.EnumFlagsField(_buildOptions); } GUILayout.Space(5); using (var h = new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("是否打Release包:", style); GUILayout.Space(15); bool curValue = _isRelease; _isRelease = EditorGUILayout.Toggle(_isRelease); if (_isRelease) { _buildOptions = BuildOptions.None; } else { if (curValue) { _buildOptions = BuildOptions.AllowDebugging | BuildOptions.Development; } } } GUILayout.Space(5); using (var h = new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("打包资源完整完整包体:", style); GUILayout.Space(15); _isCompletePack = EditorGUILayout.Toggle(_isCompletePack); } GUILayout.Space(5); using (var h = new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("重新打包AssetBundle:", style); GUILayout.Space(15); _isBuildAssetBundle = EditorGUILayout.Toggle(_isBuildAssetBundle); if (_isRelease) { _isBuildAssetBundle = true; } } GUILayout.Space(20); GUI.backgroundColor = Color.green; if (GUILayout.Button("开始打包", GUILayout.Height(30))) { if (EditorUtility.DisplayDialog("提示", "确认开始打包?", "确认")) { _locationPathName = EditorUtility.OpenFolderPanel("选择输出文件夹", _locationPathName, ""); EditorApplication.delayCall += () => { if (string.IsNullOrEmpty(_locationPathName)) { return; } if (Directory.Exists(_locationPathName)) { Directory.Delete(_locationPathName, true); } Directory.CreateDirectory(_locationPathName); if (_isBuildAssetBundle) { AssetBundleGenerate.GenerateAll(); } if (_isCompletePack) { ExportABPackage.ExportAssetBundlePackage(); } else { if (File.Exists(ExportABPackage.ZipStreamingAssetsPath)) { File.Delete(ExportABPackage.ZipStreamingAssetsPath); } } string report = string.Empty; try { string extensionName = string.Empty; switch (_platform) { case BuildPlatform.Android: extensionName = ".apk"; break; case BuildPlatform.Windows64: extensionName = ".exe"; break; default: break; } BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions(); buildPlayerOptions.scenes = EditorBuildSettingsScene.GetActiveSceneList(EditorBuildSettings.scenes); buildPlayerOptions.locationPathName = _locationPathName + "/" + PlayerSettings.productName + extensionName; buildPlayerOptions.target = (BuildTarget)_platform; buildPlayerOptions.options = _buildOptions; report = BuildPipeline.BuildPlayer(buildPlayerOptions); } catch (Exception e) { LogHelper.PrintError(string.Format("打包失败:{0},{1}.", report, e.ToString())); return; } LogHelper.PrintError(string.Format("打包成功:{0}.", report)); }; Close(); } } GUI.backgroundColor = color; } GUILayout.Space(10); using (var vv = new EditorGUILayout.VerticalScope(GUI.skin.box)) { EditorGUILayout.LabelField("打热更包", style); GUILayout.Space(5); } } }
public static int SceneCompare(EditorBuildSettingsScene x, EditorBuildSettingsScene y) { return(-x.path.CompareTo(y.path)); }
/// <summary> /// Entry point for Unity Cloud builds. /// </summary> /// <remarks> /// If you don't configure anything, Unity Cloud Build will build without a /// profile, all Options will use their default value and will be removed. /// /// Add the name of the Build Profile you want to build with to the target name /// in Unity Cloud Build, enclosed in double underscores, e.g. `__Profile Name__`. /// Note that since the target name can contain only alphanumeric characters, /// spaces, dashes and underscores, those characters cannot appear in the profile /// name either. /// /// Also note that the ability for Options to set build options is limited, /// currently only setting a custom scene list is supported. /// </remarks> public static void UnityCloudBuild(BuildManifestObject manifest) { BuildType = TrimmerBuildType.CloudBuild; Debug.Log("UnityCloudBuild: Parsing profile name..."); // Get profile name from could build target name string targetName; if (!manifest.TryGetValue("cloudBuildTargetName", out targetName)) { Debug.LogError("Could not get target name from cloud build manifest."); } else { var match = Regex.Match(targetName, @"__([\w\-. ]+)__"); if (match.Success) { targetName = match.Groups[1].Value; Debug.Log("Parsed build profile name from target name: " + targetName); } } Debug.Log("UnityCloudBuild: Looking for profile..."); BuildProfile buildProfile = null; if (!string.IsNullOrEmpty(targetName)) { buildProfile = BuildProfile.Find(targetName); if (buildProfile == null) { Debug.LogError("Build Profile named '" + targetName + "' could not be found."); return; } } if (buildProfile == null) { Debug.LogWarning("No Build Profile selected. Add the Build Profile enclosed in double underscores (__) to the target name."); return; } Debug.Log("UnityCloudBuild: Running PrepareBuild callbacks..."); // Prepare build var options = GetDefaultOptions(EditorUserBuildSettings.activeBuildTarget); currentProfile = buildProfile; // Run options' PrepareBuild foreach (var option in GetCurrentEditProfile().OrderBy(o => o.PostprocessOrder)) { if ((option.Capabilities & OptionCapabilities.ConfiguresBuild) == 0) { continue; } var inclusion = buildProfile == null ? OptionInclusion.Remove : buildProfile.GetInclusionOf(option, options.target); options = option.PrepareBuild(options, inclusion); } // Cloud Build doesn't allow changing BuildPlayerOptions.extraScriptingDefines, // so we have to apply scripting define symbols to player settings ApplyScriptingDefineSymbolsToPlayerSettings(buildProfile, options.target); Debug.Log("UnityCloudBuild: Apply scenes..."); // Apply scenes if (options.scenes != null && options.scenes.Length > 0) { var scenes = new EditorBuildSettingsScene[options.scenes.Length]; for (int i = 0; i < scenes.Length; i++) { scenes[i] = new EditorBuildSettingsScene( options.scenes[i], true ); } EditorBuildSettings.scenes = scenes; } OptionHelper.currentBuildOptions = options; Debug.Log("UnityCloudBuild: Done!"); }
private static void OnInitialize() { var sceneAssets = new List <string>(); var rules = BuildScript.GetBuildRules(); foreach (var guid in AssetDatabase.FindAssets("t:Scene", new[] { "Assets" })) { var assetPath = AssetDatabase.GUIDToAssetPath(guid); sceneAssets.Add(assetPath); } var patches = new List <Patch>(); var assets = new List <AssetRef>(); var searchPaths = new List <string>(); var dirs = new Dictionary <string, int>(); foreach (var asset in rules.assets) { if (!File.Exists(asset.name)) { continue; } var dir = Path.GetDirectoryName(asset.name); if (!string.IsNullOrEmpty(dir)) { if (!searchPaths.Contains(dir)) { dirs[dir] = searchPaths.Count; searchPaths.Add(dir); } } var ar = new AssetRef { name = Path.GetFileName(asset.name), bundle = -1, dir = dirs[dir] }; assets.Add(ar); } var scenes = new EditorBuildSettingsScene[sceneAssets.Count]; for (var index = 0; index < sceneAssets.Count; index++) { var asset = sceneAssets[index]; scenes[index] = new EditorBuildSettingsScene(asset, true); var dir = Path.GetDirectoryName(asset); if (!searchPaths.Contains(dir)) { searchPaths.Add(dir); } } for (var i = 0; i < rules.patches.Count; i++) { var item = rules.patches[i]; var patch = new Patch(); patch.name = item.name; patches.Add(patch); } var developVersions = new Versions(); developVersions.dirs = searchPaths.ToArray(); developVersions.assets = assets; developVersions.patches = patches; Assets.basePath = Environment.CurrentDirectory.Replace("\\", "/") + "/" + BuildScript.outputPath + "/"; Assets.assetLoader = AssetDatabase.LoadAssetAtPath; Assets.versionsLoader += () => developVersions; Assets.onAssetLoaded += rules.OnLoadAsset; Assets.onAssetUnloaded += rules.OnUnloadAsset; rules.BeginSample(); EditorBuildSettings.scenes = scenes; EditorApplication.playModeStateChanged += EditorApplicationOnplayModeStateChanged; }
void OnGUI() { EditorGUILayout.HelpBox("The tool will serialize scene generating a new cooked scene and label scene assets automatically.Then, you can use SceneBuilder tool to build these assets!", MessageType.Info); if (GUILayout.Button("Serialize Scene")) { string SceneOriginalName = EditorSceneManager.GetActiveScene().name; #region Save As New Scene EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene(), "Assets/SceneBuilderSubAssets/Res/Cooked/Scene/" + SceneOriginalName + "_Cooked.unity", true); EditorSceneManager.OpenScene("Assets/SceneBuilderSubAssets/Res/Cooked/Scene/" + SceneOriginalName + "_Cooked.unity"); #endregion GameObject[] SceneObjects = GameObject.FindObjectsOfType <GameObject>(); List <GameObject> ScenePrefabsGameObjects = new List <GameObject>(); foreach (GameObject sceneObject in SceneObjects) { GameObject PrefabRoot = PrefabUtility.FindRootGameObjectWithSameParentPrefab(sceneObject); //场景中物体父对象 if (PrefabUtility.GetPrefabType(sceneObject) != PrefabType.None) { if (PrefabRoot.tag == "NotAllowBuild") { continue; } if (ScenePrefabsGameObjects.Contains(PrefabRoot)) { Debug.Log(PrefabRoot.name + "Built"); continue; } #region Genrerate new ReplaceObject with SceneAssetPrefab.cs GameObject ReplaceObject = new GameObject(PrefabRoot.name + "_CookedResource"); ReplaceObject.transform.SetParent(PrefabRoot.transform); ReplaceObject.transform.localScale = new Vector3(1, 1, 1); ReplaceObject.transform.localPosition = Vector3.zero; ReplaceObject.transform.localEulerAngles = Vector3.zero; ReplaceObject.transform.SetParent(PrefabRoot.transform.parent); ReplaceObject.isStatic = PrefabRoot.isStatic; ReplaceObject.layer = PrefabRoot.layer; ReplaceObject.transform.tag = PrefabRoot.transform.tag; #region SetUp SceneAssetPrefab SceneAssetPrefab sceneAssetPrefab = ReplaceObject.AddComponent <SceneAssetPrefab>(); List <SceneAssetPrefab.MeshParameter> MeshParameters = new List <SceneAssetPrefab.MeshParameter>(); #region Save LightMap data if (PrefabRoot.GetComponentsInChildren <MeshRenderer>().Length > 0) { foreach (MeshRenderer meshRender in PrefabRoot.GetComponentsInChildren <MeshRenderer>()) { SceneAssetPrefab.MeshParameter MeshParameter = new SceneAssetPrefab.MeshParameter(); if (meshRender.transform == PrefabRoot.transform) { MeshParameter.RendererPathinChild = false; } else { MeshParameter.RendererPathinChild = true; Transform Current = meshRender.transform; string ChildPath = ""; List <string> Relation = new List <string>(); while (Current != PrefabRoot.transform) { Relation.Add(Current.name); Current = Current.parent; } for (int i = Relation.Count - 1; i >= 0; i--) { ChildPath += Relation[i] + "/"; } MeshParameter.RendererPath = ChildPath; } MeshParameter.LightingMapIndex = meshRender.lightmapIndex; MeshParameter.LightingMapTilingOffset = meshRender.lightmapScaleOffset; MeshParameter.reflectionusage = meshRender.reflectionProbeUsage; MeshParameters.Add(MeshParameter); } } sceneAssetPrefab.assetName = PrefabUtility.GetPrefabParent(PrefabRoot).name; sceneAssetPrefab.meshParameters = MeshParameters.ToArray(); sceneAssetPrefab.assetBundleName = AssetNameCorretor(AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(PrefabUtility.GetPrefabParent(PrefabRoot)))); sceneAssetPrefab.assetBundleVariant = "sceneobject"; #endregion #endregion #endregion if (!ScenePrefabsGameObjects.Contains(PrefabRoot)) { ScenePrefabsGameObjects.Add(PrefabRoot); } } } List <GameObject> GameObjectsInAsset = new List <GameObject>(); foreach (GameObject scenePrefab in ScenePrefabsGameObjects) { GameObject GameObjectInAsset = PrefabUtility.GetPrefabParent(scenePrefab) as GameObject; if (!GameObjectsInAsset.Contains(GameObjectInAsset)) { GameObjectsInAsset.Add(GameObjectInAsset); } } SceneData sceneData = ScriptableObject.CreateInstance <SceneData>(); sceneData.SceneObjectReferences = GameObjectsInAsset.ToArray(); System.IO.DirectoryInfo Dir = System.IO.Directory.CreateDirectory("Assets/SceneBuilderSubAssets/Cooks/Map/"); AssetDatabase.CreateAsset(sceneData, "Assets/SceneBuilderSubAssets/Cooks/Map/" + SceneOriginalName + ".asset"); AssetDatabase.SaveAssets(); EditorUtility.FocusProjectWindow(); Selection.activeObject = sceneData; foreach (GameObject scenePrefab in ScenePrefabsGameObjects) { //if (scenePrefab != null && !Reimported.Contains(PrefabUtility.GetPrefabParent(scenePrefab))) //{ // Reimported.Add(PrefabUtility.GetPrefabParent(scenePrefab)); // Debug.Log(scenePrefab.name + "Asset Reimported!"); // AssetImporter assetImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(PrefabUtility.GetPrefabParent(scenePrefab))); // string AssetPathToGUID = AssetNameCorretor(AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(PrefabUtility.GetPrefabParent(scenePrefab)))); // assetImporter.assetBundleName = AssetPathToGUID; // assetImporter.assetBundleVariant = "sceneobject"; //} DestroyImmediate(scenePrefab); } EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); EditorSceneManager.SaveOpenScenes(); string AllScenes = "\n Current Active Scenes:"; bool AddFlag = true; for (int i = 0; i < EditorBuildSettings.scenes.Length; i++) { AllScenes += "\n -" + EditorBuildSettings.scenes[i].path; if (EditorBuildSettings.scenes[i].path == EditorSceneManager.GetActiveScene().path) { AddFlag = false; } } if (AddFlag) { if (EditorUtility.DisplayDialog("Add to BuildSetting", "Do you want to add this cooked scene to BuildSetting?" + AllScenes, "Yes", "No,Thanks")) { EditorBuildSettingsScene[] original = EditorBuildSettings.scenes; EditorBuildSettingsScene[] newSettings = new EditorBuildSettingsScene[original.Length + 1]; System.Array.Copy(original, newSettings, original.Length); newSettings[newSettings.Length - 1] = new EditorBuildSettingsScene(EditorSceneManager.GetActiveScene().path, true); EditorBuildSettings.scenes = newSettings; } } //EditorSceneManager.SaveOpenScenes (); } }
public static void BuildAll() { string appId = GetArg("-AppID"); string buildScene = GetArg("-BuildScene"); string targetProjetPath = GetArg("-TargetProjectPath"); string targetPlatform = GetArg("-TargetPlatform"); string compilerParam = GetArg("-CompilerParam"); string version = GetArg("-version"); Debug.Log("AppID=[" + appId + "]"); Debug.Log("Build Scene [" + buildScene + "]"); Debug.Log("Path=[" + targetProjetPath + "]"); Debug.Log("Platform=[" + targetPlatform + "]"); Debug.Log("version=" + version); if (appId == null) { Debug.Log("appId can not be null!"); EditorApplication.Exit(1); return; } PlayerSettings.productName = appId; EditorUserBuildSettings.development = false; EditorUserBuildSettings.allowDebugging = false; BuildPlayerOptions option = new BuildPlayerOptions(); option.options = BuildOptions.None; // 设置需要编译的场景 if (buildScene != null) { option.scenes = new[] { buildScene }; } else { List <string> sceneList = new List <string>(); for (int i = 0; i < EditorBuildSettings.scenes.Length; i++) { EditorBuildSettingsScene scene = EditorBuildSettings.scenes[i]; if (scene.enabled) { sceneList.Add(scene.path); Debug.Log("Need Scene -> " + scene.path); } } option.scenes = sceneList.ToArray(); } // 设置平台信息 BuildTargetGroup group = BuildTargetGroup.WSA; if (targetPlatform == "HoloLens" || targetPlatform == "Surface") { group = BuildTargetGroup.WSA; EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTarget.WSAPlayer); EditorUserBuildSettings.wsaSDK = WSASDK.UWP; if (targetPlatform == "HoloLens") { EditorUserBuildSettings.wsaSubtarget = WSASubtarget.HoloLens; PlayerSettings.virtualRealitySupported = true; //VRSettings.LoadDeviceByName("HoloLens"); //VRSettings.enabled = true; } else if (targetPlatform == "Surface") { EditorUserBuildSettings.wsaSubtarget = WSASubtarget.PC; PlayerSettings.virtualRealitySupported = false; } EditorUserBuildSettings.wsaUWPBuildType = WSAUWPBuildType.D3D; EditorUserBuildSettings.wsaBuildAndRunDeployTarget = WSABuildAndRunDeployTarget.LocalMachine; EditorUserBuildSettings.wsaGenerateReferenceProjects = true; option.target = BuildTarget.WSAPlayer; // 设置产出路径 option.locationPathName = targetProjetPath; PlayerSettings.runInBackground = false; } else if (targetPlatform == "PC") { group = BuildTargetGroup.Standalone; EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTarget.StandaloneWindows64); PlayerSettings.apiCompatibilityLevel = ApiCompatibilityLevel.NET_2_0; option.target = BuildTarget.StandaloneWindows64; // 设置产出路径 string ending = ""; if (!targetProjetPath.EndsWith("/")) { ending = "/"; } option.locationPathName = targetProjetPath + ending + appId + ".exe"; // PC端设置为可背景运行 PlayerSettings.runInBackground = true; } else { Debug.LogError("[Build]No Such Platform!!"); return; } // 设置编译参数 string define = PlayerSettings.GetScriptingDefineSymbolsForGroup(group); // 先排除可能需要排除的编译参数 define = RemoveParam(define, "ME_LIVE_ACTIVE"); // 再添加编译参数 if (compilerParam != null) { define += ";" + compilerParam; PlayerSettings.SetScriptingDefineSymbolsForGroup(group, define); } // 设置路径 Debug.Log(targetProjetPath); if (!System.IO.Directory.Exists(targetProjetPath)) { System.IO.Directory.CreateDirectory(targetProjetPath); } // 开始编译 string buildError = BuildPipeline.BuildPlayer(option); if (buildError.StartsWith("Error")) { Debug.Log("Build Error! " + buildError); EditorApplication.Exit(1); return; } else { Debug.Log("Try to change version!"); } // 修改版本号 if (targetPlatform == "HoloLens" || targetPlatform == "Surface") { SetPackageNameAndVersion(targetProjetPath, appId, version); } }
/// <summary> /// Called on GUI events. /// </summary> internal void OnGUI() { EditorGUILayout.BeginVertical(); this.scrollPos = EditorGUILayout.BeginScrollView(this.scrollPos, false, false); GUILayout.Label(string.Format("Scenes In Build Settings ({0} opened)", EditorSceneManager.sceneCount), EditorStyles.boldLabel); for (int i = 0; i < EditorBuildSettings.scenes.Length; i++) { EditorBuildSettingsScene buildSettingsScene = EditorBuildSettings.scenes[i]; string sceneName = Path.GetFileNameWithoutExtension(buildSettingsScene.path); if (!buildSettingsScene.enabled) { sceneName += " (disabled)"; } EditorGUILayout.BeginHorizontal(); { using (new EditorGUI.DisabledScope(IsSceneOpen(buildSettingsScene))) { GUIContent content = new GUIContent(sceneName, AssetPreview.GetMiniTypeThumbnail(typeof(SceneAsset))); GUIStyle style = new GUIStyle(GUI.skin.GetStyle("Button")) { alignment = TextAnchor.MiddleLeft, stretchWidth = true, fixedHeight = 25 }; bool pressed = GUILayout.Button(content, style); if (pressed) { if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { EditorSceneManager.OpenScene(buildSettingsScene.path); } } } } if (!IsSceneOpen(buildSettingsScene)) { GUIContent content = new GUIContent("Add", "Adds the scene to the current open ones"); GUIStyle style = new GUIStyle(GUI.skin.GetStyle("Button")) { alignment = TextAnchor.MiddleLeft, fixedWidth = 60, fixedHeight = 25 }; bool pressed = GUILayout.Button(content, style); if (pressed) { EditorSceneManager.OpenScene(buildSettingsScene.path, OpenSceneMode.Additive); } } else if (EditorSceneManager.sceneCount > 1) { GUIContent content = new GUIContent("Remove", "Unloads and removes the scene"); GUIStyle style = new GUIStyle(GUI.skin.GetStyle("Button")) { alignment = TextAnchor.MiddleLeft, fixedWidth = 60, fixedHeight = 25 }; bool pressed = GUILayout.Button(content, style); if (pressed) { Scene scene = FromBuildSettingsScene(buildSettingsScene); if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { EditorSceneManager.CloseScene(scene, true); } } } EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndScrollView(); EditorGUILayout.EndVertical(); }
void OnGUI() { if (projectList == null) { projectList = new ReorderableList(scenesInProject, typeof(SceneInfo), false, false, false, false); projectList.drawHeaderCallback = (Rect rect) => { EditorGUI.LabelField(rect, "Scenes In Project", EditorStyles.boldLabel); }; projectList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { var sceneInfo = scenesInProject[index]; EditorGUI.LabelField(new Rect(rect.x, rect.y, rect.width - 60, rect.height), sceneInfo.name); if (GUI.Button(new Rect(rect.width - 60, rect.y, 20, rect.height), "P", GUIStyle.none)) { EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath <SceneAsset>(sceneInfo.path)); } if (GUI.Button(new Rect(rect.width - 40, rect.y, 20, rect.height), "O", GUIStyle.none)) { List <SceneInfo> scenes = this.GetScenesInHierarchy(); //得到 Hierarchy 中的 已加载的 场景 int sceneIndex = scenes.FindIndex(v => v.path == sceneInfo.path); //确认当前请求添加的场景 的状态 if (sceneIndex == -1) { bool savemodified = EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); if (savemodified) //After the user responds positively (with or without saving), open the scene he specified. { int switchIndex = EditorUtility.DisplayDialogComplex("OpenSceneMode", "Addition:Add scene and keep the loaded scene\nSingle:Will Remove all the loaded scene of hierarchy", "Single", "Cancel", "Addition"); switch (switchIndex) { case 0: EditorSceneManager.OpenScene(sceneInfo.path); break; case 2: EditorSceneManager.OpenScene(sceneInfo.path, OpenSceneMode.Additive); break; case 1: default: this.ShowNotification(new GUIContent("Aborting!")); break; } } else { this.ShowNotification(new GUIContent("Aborting!")); } } else //If it is stay in the hierarchy,no matter whether it is load or unload, ping this scene { EditorGUIUtility.PingObject(scenes[sceneIndex].instanceID); this.ShowNotification(new GUIContent("This scene already in the hierarchy!")); } } if (GUI.Button(new Rect(rect.width - 20, rect.y, 20, rect.height), "A", GUIStyle.none)) { int sceneIndex = SceneUtility.GetBuildIndexByScenePath(sceneInfo.path); if (sceneIndex == -1) { var tmpSceneIn = EditorBuildSettings.scenes.ToList(); tmpSceneIn.Add(new EditorBuildSettingsScene(sceneInfo.path, true)); EditorBuildSettings.scenes = tmpSceneIn.ToArray(); ADB.Refresh(); } else { this.ShowNotification(new GUIContent("This scene already in the buildlist!")); } } }; } if (settingList == null) { settingList = new ReorderableList(scenesInSettings, typeof(SceneInfo), true, false, false, true); settingList.onReorderCallback = (ReorderableList list) => { EditorBuildSettings.scenes = list.list.Cast <SceneInfo>() .Select(scene => { var editorScene = new EditorBuildSettingsScene(); editorScene.enabled = scene.enabledInSettings; editorScene.path = scene.path; return(editorScene); }) .ToArray(); }; settingList.drawHeaderCallback = (Rect rect) => { EditorGUI.LabelField(rect, "Scenes In Setting", EditorStyles.boldLabel); }; settingList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { var sceneInfo = scenesInSettings[index]; sceneInfo.enabledInSettings = GUI.Toggle(new Rect(rect.x, rect.y, 14, rect.height), sceneInfo.enabledInSettings, string.Empty); var tmpScenesInSetting = EditorBuildSettings.scenes.ToList(); tmpScenesInSetting.Where(scene => scene.path == sceneInfo.path).First().enabled = sceneInfo.enabledInSettings; EditorGUI.LabelField(new Rect(rect.x + 14, rect.y, rect.width - 34, rect.height), sceneInfo.name); EditorGUI.LabelField(new Rect(rect.width - 8, rect.y, 20, rect.height), index.ToString()); if (GUI.Button(new Rect(rect.width - 65, rect.y, 20, rect.height), "PH", GUIStyle.none)) { int id = this.GetInstanceId(sceneInfo); if (id != -1) { RemoveNotification(); EditorGUIUtility.PingObject(id); } else { ShowNotification(new GUIContent("The scene you pinged is not in hierarchy!")); } } if (GUI.Button(new Rect(rect.width - 30, rect.y, 20, rect.height), "PP", GUIStyle.none)) { var assetObj = ADB.LoadAssetAtPath <SceneAsset>(sceneInfo.path); if (null != assetObj) { RemoveNotification(); EditorGUIUtility.PingObject(assetObj); } } }; settingList.onRemoveCallback = (ReorderableList list) => { if (EditorUtility.DisplayDialog("Attention:", "Really want to remove this scene from the BuildList?", "Yes", "No")) { var tempList = EditorBuildSettings.scenes.ToList(); tempList.RemoveAt(list.index); tempList.TrimExcess(); EditorBuildSettings.scenes = tempList.ToArray(); ReorderableList.defaultBehaviours.DoRemoveButton(list); } }; } scenesInProject = GetScenesInProject(); scenesInSettings = GetScenesInSettings(); projectList.list = scenesInProject; settingList.list = scenesInSettings; // settingScrollPosition = EditorGUILayout.BeginScrollView(settingScrollPosition); settingList.DoLayoutList(); //EditorGUILayout.EndScrollView(); projectScrollPosition = EditorGUILayout.BeginScrollView(projectScrollPosition); projectList.DoLayoutList(); EditorGUILayout.EndScrollView(); }