public static string CreateScene(string path, params GameObject[] gameObjects) { var scenePath = path + ".unity"; // PROBLEM: When using NewSceneMode.Single during import assertion "GetApplication().MayUpdate()" fails // SOLUTION: During import, using Additive loading works. // PROBLEM: InvalidOperationException: Cannot create a new scene additively with an untitled scene unsaved. // NOTE: This can occur when the previously opened scene has ceased to exist, in particular when a project is opened. var scene = EditorSceneManager.GetActiveScene(); var addNew = scene.name.Length > 0 && scene.path.Length > 0 && scene.path != scenePath; // scene.IsValid() will be true even when path and name are empty if (addNew) { scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); } else { // Remove all default scene objects foreach (var rootObject in scene.GetRootGameObjects()) { EP.Destroy(rootObject); } } EditorSceneManager.SetActiveScene(scene); // Add objects to scene foreach (var gameObject in gameObjects) { EP.Instantiate(gameObject); } // WARNING: If scene is created during asset import physics computations will not be initialized // PROBLEM: At end of import the open scene will have been modified, so a pop-up will appear. // SOLUTION: After loading the scene in additive mode, close it. EditorSceneManager.SaveScene(scene, scenePath); if (addNew) { EditorSceneManager.CloseScene(scene, true); } return(scenePath); }
private static void SaveTrunksAsScenes(string sceneName, SceneTrunkMgr sceneTrunkMgr, List <TerrainTrunk> trunks) { string sceneSubDir = string.Format("Assets/Scenes/{0}_Trunks", sceneName); if (System.IO.Directory.Exists(sceneSubDir)) { System.IO.Directory.Delete(sceneSubDir, true); } System.IO.Directory.CreateDirectory(sceneSubDir); for (int i = 0; i < trunks.Count; i++) { var trunk = trunks[i]; string trunkSceneName = string.Format("{0}_{1}_{2}", sceneName, trunk.xIndex, trunk.zIndex); string trunkScenePath = string.Format("{0}/{1}.unity", sceneSubDir, trunkSceneName); var trunkScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); EditorSceneManager.SetActiveScene(trunkScene); trunk.terrian.transform.parent = null; EditorSceneManager.MoveGameObjectToScene(trunk.terrian.gameObject, trunkScene); EditorSceneManager.SaveScene(trunkScene, trunkScenePath); EditorSceneManager.CloseScene(trunkScene, true); var trunkAsset = AssetImporter.GetAtPath(trunkScenePath); var trunkName = string.Format("trunk_{0}_{1}.bundle", trunk.xIndex, trunk.zIndex); trunkAsset.assetBundleName = string.Format("scenes/{0}/{1}", sceneName, trunkName); sceneTrunkMgr.entries[i] = new SceneTrunkDataEntry() { x = trunk.xIndex, z = trunk.zIndex, trunkBundlePath = trunkAsset.assetBundleName, trunkName = trunkSceneName, }; } }
public override void OnInspectorGUI() { DrawDefaultInspector(); if (GUILayout.Button("Rebuild List") == true) { for (int i = m_Data.List.Count - 1; i >= 0; i--) { if (m_Data.List[i] == null) { m_Data.List.RemoveAt(i); } } m_Data.Dic.Clear(); for (int i = 0; i < m_Data.List.Count; i++) { m_Data.Dic.Add(m_Data.List[i].name, m_Data.List[i]); } } GUILayout.BeginVertical("box"); m_Data.m_BuildScenePath = EditorGUILayout.TextField("Build Scene Path", m_Data.m_BuildScenePath); m_Data.m_BuildSceneName = EditorGUILayout.TextField("Build Scene Name", m_Data.m_BuildSceneName); if (GUILayout.Button("Save Scene As") == true) { if (m_Data.m_BuildSceneName.Length > 0) { EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene(), m_Data.m_BuildScenePath + "/" + m_Data.m_BuildSceneName + ".unity", false); } } GUILayout.EndVertical(); if (GUI.changed) { EditorUtility.SetDirty(m_Data); } }
protected void CheckAndCreateScene() { if (EditorApplication.isPlaying) { Debug.LogWarning("Cannot create scenes while in play mode. Exit play mode first."); return; } Scene currentActiveScene = SceneManager.GetActiveScene(); if (currentActiveScene.isDirty) { string title = currentActiveScene.name + " Has Been Modified"; string message = "Do you want to save the changes you made to " + currentActiveScene.path + "?\nChanges will be lost if you don't save them."; int option = EditorUtility.DisplayDialogComplex(title, message, "Save", "Don't Save", "Cancel"); if (option == 0) { EditorSceneManager.SaveScene(currentActiveScene); } else if (option == 2) { return; } } switch (index) { case 0: CreateScene("_TemplateScene"); break; case 1: CreateScene("_DungeonTemplateScene"); break; default: Debug.LogError("Unrecognized Option"); break; } }
static void UnloadAllScenesExcept(string sceneName) { List <String> scenesThatShouldRemainLoaded = LevelManager.instance.allLevels .Find(lvl => lvl.level == LevelManager.instance.startingScene).connectedLevels .ComposableAdd(LevelManager.instance.startingScene) .Select(lvl => lvl.ToName()) .ToList(); int numScenes = SceneManager.sceneCount; List <Scene> scenesThatGotUnloaded = new List <Scene>(); for (int i = 0; i < numScenes; i++) { Scene scene = SceneManager.GetSceneAt(i); // Save all open scenes upon entering play mode if (scene.isDirty) { EditorSceneManager.SaveScene(scene); } if (scene.name != sceneName && !scenesThatShouldRemainLoaded.Contains(scene.name)) { scenesThatGotUnloaded.Add(scene); } } string saveData = string.Join(",", scenesThatGotUnloaded.Select(s => s.path)); foreach (var sceneToUnload in scenesThatGotUnloaded) { try { EditorSceneManager.CloseScene(sceneToUnload, true); } catch (Exception e) { Debug.LogError($"Failed unloading scene {sceneToUnload}, details: {e}"); } } PlayerPrefs.SetString(playerPrefsKey, saveData); }
private IEnumerator DoActionToScene(PathData pathData, Func <ParticleSystemRenderer, string> action) { var scenePath = pathData.FilePath; var scene = SceneManager.GetSceneByPath(scenePath); if (!scene.IsValid() && AssetDatabase.LoadAssetAtPath <SceneAsset>(scenePath)) { scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive); } if (!scene.IsValid()) { Debug.Log($"Scene is not valid: {scenePath}"); EditorSceneManager.CloseScene(scene, true); } var roots = scene.GetRootGameObjects(); foreach (var go in roots) { var renderers = go.GetComponentsInChildren <ParticleSystemRenderer>(true); CheckMissingObject(go); foreach (var renderer in renderers) { if (TransformTool.GetPath(renderer.transform) == pathData.RendererPath) { string error = action.Invoke(renderer); if (!string.IsNullOrEmpty(error)) { Debug.LogWarning($"Error: {error} at 【{scenePath}】{TransformTool.GetPath(renderer.transform)}"); } } } } EditorSceneManager.SaveScene(scene); EditorSceneManager.CloseScene(scene, true); yield break; }
private void SaveData() { foreach (Node _node in nodes) { TriggerNodeInfo script = sceneItems.Where(t => t.ID == _node.ID).First(); GameObject obj = script.gameObject; obj.name = "Generated_Node_" + script.ID; //The name shows the node ID to make it easier. List <Vector2> v2Cons = null; if (_node.nodeCons.Count > 0) { v2Cons = new List <Vector2>(); foreach (Connection con in _node.nodeCons) { v2Cons.Add(new Vector2(con.inPoint.ID, con.outPoint.ID)); } } script.SaveTriggerData(_node.rect, _node.ID, _node.title, _node.showAudio, _node.playedAudioClips, _node.delays, v2Cons, _node.pathType, _node.scrollViewVector, _node.worldPosition); } ConnectionsManager conManager = GetConnectionManager(); List <ConnectionInfo> conList = new List <ConnectionInfo>(); foreach (Connection con in connections) { conList.Add(new ConnectionInfo(con.inPoint.ID, con.outPoint.ID, con.connectionType)); } conManager.SaveConnections(conList); //When the nodes and connections get saved, save the scene too to make sure everything is saved. string[] path = EditorSceneManager.GetActiveScene().path.Split(char.Parse("/")); path[path.Length - 1] = path[path.Length - 1]; bool saveOK = EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene(), string.Join("/", path)); Debug.Log("Saved the Nodes and the Scene " + (saveOK ? "Sucessfully" : "Error!")); nextSave = (float)EditorApplication.timeSinceStartup + saveTime; }
static void BuildBundles() { var importDir = @"Assets\toBundle\"; var exportDir = @"AssetBundles\"; //build all assetBundles if (AssetDatabase.IsValidFolder(exportDir) == false) { Directory.CreateDirectory(exportDir); } AssetDatabase.RemoveUnusedAssetBundleNames(); var subDirectories = Directory.GetDirectories(importDir); foreach (string m in subDirectories) { var meshes = Directory.GetFiles(m); //loop through each file in dir and find .fbx files foreach (string a in meshes) { if (Path.GetExtension(a) == ".fbx") { Scene newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); var obj = AssetDatabase.LoadAssetAtPath <GameObject>(a); var newObj = GameObject.Instantiate(obj); newObj.name = obj.name; var sceneName = m + "\\" + obj.name + ".unity"; EditorSceneManager.SaveScene(newScene, sceneName); AssetImporter asset = AssetImporter.GetAtPath(sceneName); asset.assetBundleName = obj.name + ".unity3d"; asset.SaveAndReimport(); BuildPipeline.BuildAssetBundles(exportDir, BuildAssetBundleOptions.None, BuildTarget.WSAPlayer); } } } }
public IEnumerator GameObjectInScene1WithOperation_MoveOperationToGameObjectInScene2_OperationOnlyExistsInScene2() { var scene2 = TestUtility.defaultScene; var scene2GameObject = new GameObject(); EditorSceneManager.SaveScene(scene2, TestUtility.tempFilename); var scene1 = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); EditorSceneManager.SetActiveScene(scene1); var scene1GameObject = new GameObject(); var operation = TestUtility.CreateUndoableGameObjectWithOperation(); var operationGameObject = operation.gameObject; operation.transform.parent = scene1GameObject.transform; Assert.AreEqual(0, CSGManager.TreeBranchCount, "Expected 0 TreeBranches to Exist"); Assert.AreEqual(0, CSGManager.TreeNodeCount, "Expected 0 TreeNodes to Exist"); yield return(null); Assert.AreEqual(1, CSGManager.TreeBranchCount, "Expected 1 TreeBranch to Exist"); Assert.AreEqual(2, CSGManager.TreeNodeCount, "Expected 2 TreeNodes to Exist"); Assert.AreEqual(scene1, operation.hierarchyItem.Scene); operation.transform.parent = scene2GameObject.transform; yield return(null); Assert.AreEqual(1, CSGManager.TreeBranchCount, "Expected 1 TreeBranch to Exist"); Assert.AreEqual(2, CSGManager.TreeNodeCount, "Expected 2 TreeNodes to Exist"); Assert.AreEqual(scene2, operation.gameObject.scene, "Operation is not part of expected scene"); Assert.AreEqual(scene2, operation.hierarchyItem.Scene, "Operation is not registered to expected scene"); Assert.AreEqual(0, CSGNodeHierarchyManager.RootCount(scene1)); Assert.AreEqual(1, CSGNodeHierarchyManager.RootCount(scene2)); // make sure test runner doesn't puke on its own bugs EditorSceneManager.NewScene(NewSceneSetup.EmptyScene); }
void OnGUI() { targetGameObject = Selection.activeGameObject; EditorGUILayout.ObjectField("Target Object", targetGameObject, typeof(GameObject), true); //EditorGUILayout.ObjectField = targetObject; textureImage = (Sprite)EditorGUI.ObjectField(new Rect(0, 30, 200, 200), "Add a Texture:", textureImage, typeof(Sprite), false); for (int i = 0; i < 12; i++) { EditorGUILayout.Space(); } //with this safety button, I make sure not to hit nothing serious; massTransformEnable = EditorGUILayout.BeginToggleGroup("Mass Transform Safety Toggle", massTransformEnable); EditorGUILayout.Space(); EditorGUILayout.Space(); buttonClick1 = GUILayout.Button("Mass Transform Button Images"); //change all button images to new image if (buttonClick1 && targetGameObject != null) { Debug.Log("Mass Transform button images"); MassTransformButtonImages(targetGameObject); EditorUtility.SetDirty(targetGameObject); EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene()); } EditorGUILayout.Space(); }
static void RecordIt() { Scene s = EditorSceneManager.GetActiveScene(); EditorSceneManager.SaveScene(s); if (s.path != firstScene) { s = EditorSceneManager.OpenScene(firstScene); } GameObject go = null; GameObject[] gos = s.GetRootGameObjects(); bool exist = false; foreach (GameObject tempgo in gos) { if (tempgo.name.Contains("DebugObject")) { exist = true; go = tempgo; break; } } if (!exist) { GameObject obj = AssetDatabase.LoadAssetAtPath(prefab, typeof(GameObject)) as GameObject; go = GameObject.Instantiate(obj); } DebugControl dc = go.GetComponent <DebugControl>(); dc.isOn = true; dc.isPlay = false; EditorApplication.isPlaying = true; }
public static void ExportCurrentSceneResource(string sceneName, bool exportPackage) { try { EditorUtility.DisplayProgressBar("Pre-Process Export Resource", "", 1 / 3f); var scene = SceneManager.GetActiveScene(); if (scene.isDirty) { EditorSceneManager.SaveScene(scene); } if (exportPackage) { ExportUnityPackage($"{sceneName}.unitypackage", scene.path); } EditorUtility.DisplayProgressBar("Building Resources", "", 2 / 3f); BuildAssetBundles(scene, sceneName); EditorUtility.DisplayProgressBar("Post-Process Export Resource", "", 3 / 3f); EditorPrefsUtils.LastBuildWin = $"{Application.temporaryCachePath}/{BuildTarget.StandaloneWindows}/{sceneName}"; EditorPrefsUtils.LastBuildMac = $"{Application.temporaryCachePath}/{BuildTarget.StandaloneOSX}/{sceneName}"; EditorPrefsUtils.LastBuildAndroid = $"{Application.temporaryCachePath}/{BuildTarget.Android}/{sceneName}"; EditorPrefsUtils.LastBuildIOS = $"{Application.temporaryCachePath}/{BuildTarget.iOS}/{sceneName}"; } catch (Exception ex) { Debug.LogError($"Export Exception : {ex.Message}"); throw; } finally { EditorUtility.ClearProgressBar(); } }
/// <summary> /// Creates a number of scenes and loads them additively for testing. Must create a minimum of 1. /// </summary> /// <param name="numScenesToCreate"></param> public static void CreateScenes(int numScenesToCreate = 1) { Debug.Assert(numScenesToCreate > 0); // Create default test scenes. // In the editor this can be done using EditorSceneManager with a default setup. // In playmode the scene needs to be set up manually. #if UNITY_EDITOR if (!EditorApplication.isPlaying) { List <Scene> additiveTestScenesList = new List <Scene>(); if (numScenesToCreate == 1) { // No need to save this scene, we're just creating one primaryTestScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single); } else { // Make the first scene single so it blows away previously loaded scenes primaryTestScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single); // Save the scene (temporarily) so we can load additively on top of it EditorSceneManager.SaveScene(primaryTestScene, primaryTestSceneTemporarySavePath); for (int i = 1; i < numScenesToCreate; i++) { string path = additiveTestSceneTemporarySavePath.Replace("#", additiveTestScenesList.Count.ToString()); // Create subsequent scenes additively Scene additiveScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Additive); additiveTestScenesList.Add(additiveScene); // Save the scene (temporarily) so we can load additively on top of it EditorSceneManager.SaveScene(additiveScene, path); } } additiveTestScenes = additiveTestScenesList.ToArray(); return; } #endif }
public static void GetSceneGuidAndObjectID(this Object source, out string sceneGuid, out int objectID) { if (AssetDatabase.Contains(source)) { sceneGuid = "None"; objectID = source.GetInstanceID(); } else if (PrefabStageUtility.GetCurrentPrefabStage() != null) { var prefab = AssetDatabase.LoadAssetAtPath <GameObject>(PrefabStageUtility.GetCurrentPrefabStage().prefabAssetPath); var components = prefab.GetComponents(source.GetType()).ToList(); components.AddRange(prefab.GetComponentsInChildren(source.GetType())); sceneGuid = "None"; int localID = source.GetLocalID(); objectID = localID; for (int i = 0; i < components.Count; i++) { if (localID == components[i].GetLocalID()) { objectID = components[i].GetInstanceID(); } } } else { var scene = (source as Component).gameObject.scene; sceneGuid = AssetDatabase.AssetPathToGUID(scene.path); objectID = source.GetLocalID(); if (objectID == 0) { if (EditorSceneManager.SaveScene(scene)) { objectID = source.GetLocalID(); } } } }
public IEnumerator GameObjectInScene1WithModel_MoveGameObjectToScene2_ModelOnlyExistsInScene2() { var scene2 = TestUtility.defaultScene; EditorSceneManager.SaveScene(scene2, TestUtility.tempFilename); var scene1 = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); EditorSceneManager.SetActiveScene(scene1); var scene1GameObject = new GameObject(); var model = TestUtility.CreateUndoableGameObjectWithModel(); var modelGameObject = model.gameObject; model.transform.parent = scene1GameObject.transform; EditorSceneManager.SaveScene(scene2, TestUtility.tempFilename2); Assert.AreEqual(0, CSGManager.TreeCount, "Expected 0 Trees to Exist"); Assert.AreEqual(0, CSGManager.TreeNodeCount, "Expected 0 TreeNodes to Exist"); yield return(null); Assert.AreEqual(1, CSGManager.TreeCount, "Expected 1 Tree to Exist"); Assert.AreEqual(1, CSGManager.TreeNodeCount, "Expected 1 TreeNode to Exist"); Assert.AreEqual(scene1, model.hierarchyItem.Scene); Undo.MoveGameObjectToScene(scene1GameObject, scene2, "Move gameObject to different scene"); yield return(null); Assert.AreEqual(1, CSGManager.TreeCount, "Expected 1 Tree to Exist"); Assert.AreEqual(1, CSGManager.TreeNodeCount, "Expected 1 TreeNode to Exist"); Assert.AreEqual(scene2, model.gameObject.scene, "Model is not part of expected scene"); Assert.AreEqual(scene2, model.hierarchyItem.Scene, "Model is not registered to expected scene"); Assert.AreEqual(0, CSGNodeHierarchyManager.RootCount(scene1)); Assert.AreEqual(1, CSGNodeHierarchyManager.RootCount(scene2)); // make sure test runner doesn't puke on its own bugs EditorSceneManager.NewScene(NewSceneSetup.EmptyScene); }
internal override void Setup(AddressableAssetSettings settings, string tempAssetFolder) { var group = settings.CreateGroup("SceneGroup", true, false, false, null, typeof(BundledAssetGroupSchema)); group.GetSchema <BundledAssetGroupSchema>().BundleNaming = BundledAssetGroupSchema.BundleNamingStyle.OnlyHash; // Create prefab var prefabGuid = CreatePrefab(Path.Combine(tempAssetFolder, String.Concat(prefabKey, ".prefab"))); var prefabEntry = settings.CreateOrMoveEntry(prefabGuid, group, false, false); prefabEntry.address = Path.GetFileNameWithoutExtension(prefabEntry.AssetPath); // Create scenes for (int i = 0; i < numScenes; i++) { var scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Additive); EditorSceneManager.SaveScene(scene, Path.Combine(tempAssetFolder, String.Concat(sceneKeys[i], ".unity"))); var guid = AssetDatabase.AssetPathToGUID(scene.path); var entry = settings.CreateOrMoveEntry(guid, group, false, false); entry.address = Path.GetFileNameWithoutExtension(entry.AssetPath); } }
protected void SaveOpenScene() { Scene managerScene = GetSceneManagerScene(); // close the other scene for (int i = EditorSceneManager.sceneCount - 1; i >= 0; i--) { Scene scene = EditorSceneManager.GetSceneAt(i); // leave manager scene if (managerScene == scene) { continue; } // now check to see if this scene is dirty if (scene.isDirty) { // save the scene EditorSceneManager.SaveScene(scene); } } }
static void EditorPlaying() { if (EditorApplication.isPlaying) { var sceneName = EditorApplication.currentScene; var path = sceneName.Split(char.Parse("/")); path[path.Length - 1] = "Temp_" + path[path.Length - 1]; var tempScene = String.Join("/", path); //EditorApplication.SaveScene(tempScene); EditorSceneManager.SaveScene(SceneManager.GetActiveScene(), "F:/project/91chengshi/client/Assets/Scene", true); EditorApplication.isPaused = false; EditorApplication.isPlaying = false; FileUtil.DeleteFileOrDirectory(EditorApplication.currentScene); FileUtil.MoveFileOrDirectory(tempScene, sceneName); FileUtil.DeleteFileOrDirectory(tempScene); EditorApplication.OpenScene(sceneName); } }
public static void Create() { var prefab = WeaverAssets.LoadWeaverAsset <GameObject>("Weaver Canvas"); if (GameObject.FindObjectOfType <EventSystem>() == null) { var eventObject = new GameObject("Event System"); if (Application.isPlaying) { GameObject.DontDestroyOnLoad(eventObject); } eventObject.AddComponent <EventSystem>(); eventObject.AddComponent <StandaloneInputModule>(); } var instance = GameObject.Instantiate(prefab, null); instance.name = prefab.name; EditorSceneManager.SaveScene(instance.scene); }
void OnInspectorUpdate() { if (DateTime.Now > nextSave || !delayEnabled) { nextSave = DateTime.Now.AddSeconds((double)delay); //save all scenes for (int i = 0; i < SceneManager.sceneCount; i++) { if (SceneManager.GetSceneAt(i).isDirty) { Scene sceneAtI = SceneManager.GetSceneAt(i); EditorSceneManager.SaveScene(sceneAtI); if (logMessage) { Debug.LogWarning("Scene \"" + sceneAtI.name + "\" Saved!"); } } } } }
static void DoCleanup() { var sceneGUIDs = AssetDatabase.FindAssets("t:Scene"); string[] scenePaths = sceneGUIDs.Select(i => AssetDatabase.GUIDToAssetPath(i)).ToArray(); for (int i = 0; i < scenePaths.Length; i++) { var scene = EditorSceneManager.OpenScene(scenePaths[i], OpenSceneMode.Additive); EditorSceneManager.MarkSceneDirty(scene); EditorSceneManager.SaveScene(scene); if (scene != EditorSceneManager.GetActiveScene()) { EditorSceneManager.UnloadSceneAsync(scene); } } //Clear cache Caching.ClearCache(); }
private Scene OutputScene(string destination) { if (_unrealMap.LevelCount > 1) { throw new System.Exception("Maps with more than one level is not supported"); } var level = _unrealMap.Levels[0]; var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); foreach (var node in level.Children) { ConvertUnrealNode(node); } EditorSceneManager.SaveScene(scene, destination); EditorSceneManager.CloseScene(scene, true); return(scene); }
static void OnSceneSaving(Scene scene, string path) { foreach (var root in scene.GetRootGameObjects()) { var installer = root.GetComponent <SceneInstaller>(); if (installer != null && installer.AutoUpdate) { Undo.RecordObject(installer, PreLoadingSystems); installer.PreLoadingSystems(); EditorUtility.SetDirty(installer); } } // I don't want to save scene twice, so i need to wait for scene detected dirty and save scene again DelayFrame(() => { if (scene.isDirty) { EditorSceneManager.SaveScene(scene); } }, DelaySaveSceneFrameCount); }
public static bool TryAddTypedProcessor(string sceneGUID) { var added = false; TryAnalyseScene(sceneGUID, scene => { var componentTypes = GetAllTypes(scene); if (!componentTypes.Contains(typeof(TypedProcessor))) { var gameObject = new GameObject("TypedProcessor"); gameObject.AddComponent <TypedProcessor>(); scene.GetRootGameObjects().Append(gameObject); Undo.RegisterCreatedObjectUndo(gameObject, "Typed processor added"); EditorSceneManager.SaveScene(scene); added = true; } }); return(added); }
void CreatPrebaf() { Scene currScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); currScene.name = path; GameObject game = AssetDatabase.LoadAssetAtPath <GameObject>("Assets/TGFramework/Prefabs/TGController.prefab"); PrefabUtility.InstantiatePrefab(game); string sceneAssetPath = "Assets/_Project/Scenes"; if (!Directory.Exists(sceneAssetPath)) { Directory.CreateDirectory(sceneAssetPath); EditorSceneManager.SaveScene(currScene, sceneAssetPath + "/" + currScene.name + ".unity"); } else { EditorSceneManager.SaveScene(currScene, "Assets/_Project/Scenes/" + currScene.name + ".unity"); } Selection.activeObject = AssetDatabase.LoadAssetAtPath("Assets/_Project/Scenes/" + currScene.name + ".unity", typeof(SceneAsset)); }
private static void ReplaceSceneObjectNames(Dictionary <string, TemplateAsset> assetDictionary, TemplateProperty property, Dictionary <string, string> replaceList) { foreach (var ta in assetDictionary.Values) { if (AssetDatabase.GetMainAssetTypeAtPath(ta.replacedDestinationPath) != typeof(SceneAsset)) { continue; } var scene = EditorSceneManager.OpenScene(ta.replacedDestinationPath, OpenSceneMode.Additive); foreach (var rootObject in scene.GetRootGameObjects()) { foreach (var t in rootObject.GetComponentsInChildren <Transform>()) { //Debug.Log(t.gameObject.name); ReplaceSceneObjectName(t.gameObject, property.replaceList, replaceList); } } EditorSceneManager.SaveScene(scene); EditorSceneManager.CloseScene(scene, true); } }
public void CreateSubSceneFromSelectionKeepsSiblingIndexInHierarchy() { var mainScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene); EditorSceneManager.SetActiveScene(mainScene); var path = Path.Combine(m_TempAssetDir, "ParentScene.unity"); EditorSceneManager.SaveScene(mainScene, path); var go1 = new GameObject("go1"); var go2 = new GameObject("go2"); var go3 = new GameObject("go3"); var siblingIndex = go2.transform.GetSiblingIndex(); Selection.activeGameObject = go2; var subsceneComponent = SubSceneContextMenu.CreateSubSceneAndAddSelection(Selection.activeGameObject, InteractionMode.AutomatedAction); Assert.AreEqual(siblingIndex, subsceneComponent.transform.GetSiblingIndex(), "The resulting SubScene GameObject should have the sibling order in the Hierarchy as the input GameObject."); }
/// <summary> /// Save the current open edited scene /// </summary> private void SaveScene() { // If the application is playing, do not save if (EditorApplication.isPlaying) { return; } // Get the active scene, set it as dirty, then save it currentScene = EditorSceneManager.GetActiveScene(); EditorSceneManager.MarkSceneDirty(currentScene); if (EditorSceneManager.SaveScene(currentScene)) { nextSaveTime = EditorApplication.timeSinceStartup + saveInterval; } else { Debug.LogWarning("Scene not saved correctly ! Another try in 30 seconds"); nextSaveTime = EditorApplication.timeSinceStartup + 30; } }
private static void AutoSaveWhenPlaymodeStarts(PlayModeStateChange obj) { if (!IsEnabled) { return; } if (EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying) { for (var i = 0; i < SceneManager.sceneCount; i++) { var scene = SceneManager.GetSceneAt(i); if (scene.isDirty) { EditorSceneManager.SaveScene(scene); } } AssetDatabase.SaveAssets(); } }
private void SaveMap() { BaseMap baseMap = (BaseMap)target; string mapName = baseMap.gameObject.name; string path = "Assets/Prefabs/Maps/" + mapName + ".prefab"; GameObject prefab = AssetDatabase.LoadAssetAtPath <GameObject>(path); if (prefab == null) { PrefabUtility.CreatePrefab(path, baseMap.gameObject); } else { PrefabUtility.ReplacePrefab(baseMap.gameObject, prefab, ReplacePrefabOptions.ReplaceNameBased); } string sceneName = "Edit" + baseMap.gameObject.name; string scenePath = "Assets/Scenes/" + sceneName + ".unity"; EditorSceneManager.SaveScene(baseMap.gameObject.scene, scenePath); ToolsHelperEditor.SetStartupScene(mapName); }