static void PasteSettingsAll() { var activeScene = EditorSceneManager.GetActiveScene(); try { for (var n = 0; n < EditorSceneManager.sceneCount; ++n) { var scene = EditorSceneManager.GetSceneAt(n); if (!scene.IsValid() || !scene.isLoaded) { continue; } EditorSceneManager.SetActiveScene(scene); PasteSettings(); } } finally { EditorSceneManager.SetActiveScene(activeScene); } }
void CreateCubeNet(CubeNet cubeNet) { if (levelScene.IsValid()) { new_scene = levelScene; } if (!new_scene.IsValid()) { new_scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); } EditorSceneManager.SetActiveScene(new_scene); string label = cubeNet.name; while (labelForCubeNetObject.ContainsKey(label)) { int index = 1; label = label + "_" + index.ToString(); index++; } GameObject parentGameObject = new GameObject(); parentGameObject.AddComponent <EditModeSnapController>(); parentGameObject.name = label; foreach (Vector3 pos in cubeNet.vectors) { GameObject tileAnchor = (GameObject)PrefabUtility.InstantiatePrefab(tileAnchorPrefab); tileAnchor.transform.SetPositionAndRotation(pos, Quaternion.identity); tileAnchor.transform.SetParent(parentGameObject.transform); } labelForCubeNetObject[label] = parentGameObject; GameObject[] selection = new GameObject[1]; selection[0] = parentGameObject; Selection.objects = selection; EditorSceneManager.SetActiveScene(activeScene); }
public static SceneAsset CreateNewScene() { UnityEngine.SceneManagement.Scene rootScene = RootScene(); SceneAsset createdScene = null; ignoreSceneEvents = true; string filename = Path.GetFileNameWithoutExtension(rootScene.path) + "_NewScene"; string scenePath = EditorUtility.SaveFilePanel( "Save New Scene", Path.GetDirectoryName(rootScene.path), filename, "unity"); if (scenePath.Length != 0) { // Make path relative. Uri fullPath = new Uri(scenePath, UriKind.Absolute); Uri relRoot = new Uri(Application.dataPath, UriKind.Absolute); scenePath = relRoot.MakeRelativeUri(fullPath).ToString(); UnityEngine.SceneManagement.Scene newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); if (EditorSceneManager.SaveScene(newScene, scenePath)) { createdScene = AssetDatabase.LoadAssetAtPath <SceneAsset>(newScene.path); } else { EditorSceneManager.CloseScene(newScene, true); EditorSceneManager.SetActiveScene(rootScene); } } ignoreSceneEvents = false; return(createdScene); }
public void SetupScenes() { // first check if the scene is already open if (EditorSceneManager.sceneCount > 1) { // multiple scenes are open, check if the second one is an extendedUI scene if (EditorSceneManager.GetSceneAt(1).name.Contains(ProWorkstationManager.extendedUIString)) { Debug.Log("extendedUI scene open already"); return; } // multiple scenes are open, but not extended UI scene Debug.Log("secondary scene is open, but is not an extendedUI scene. please close extra scenes and try again."); return; } else { // if only one scene is open var activeScene = EditorSceneManager.GetActiveScene(); EditorSceneManager.SaveOpenScenes(); Debug.Log("active scene saved!"); // first see if this scene is already the extended UI scene string secondSceneName = ""; string newPath = ""; if (activeScene.name.Contains(ProWorkstationManager.extendedUIString)) { // if the active scene is already open, try to load the regular scene secondSceneName = activeScene.name.Substring(0, activeScene.name.IndexOf(ProWorkstationManager.extendedUIString)); newPath = activeScene.path; newPath = newPath.Substring(0, newPath.LastIndexOf(ProWorkstationManager.extendedUIString)) + ".unity"; Debug.Log(secondSceneName); Debug.Log(newPath); } else { // try to load _extendedUI version of that scene instead secondSceneName = activeScene.name + ProWorkstationManager.extendedUIString; newPath = activeScene.path; newPath = newPath.Insert(newPath.LastIndexOf(".unity"), ProWorkstationManager.extendedUIString); } bool loadedSceneSuccessfully = TryLoadingScene(newPath); if (loadedSceneSuccessfully) { Debug.Log("found existing complementary scene, loading"); } else { // if it doesn't exist, create and save it Scene extendedScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); // extendedScene.name = secondSceneName; EditorSceneManager.SaveScene(extendedScene, newPath); Debug.Log("didn't find existing complementary scene, creating it"); } // set active scene to lkg one, just to fix lighting Scene lkgScene = EditorSceneManager.GetActiveScene(); for (int i = 0; i < EditorSceneManager.sceneCount; i++) { if (!EditorSceneManager.GetSceneAt(i).name.Contains(ProWorkstationManager.extendedUIString)) { lkgScene = EditorSceneManager.GetSceneAt(i); } } EditorSceneManager.SetActiveScene(lkgScene); } }
private static void OpenMultiscene(MultiScene obj, bool additive) { Scene activeScene = default(Scene); if (additive || EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { var firstUnloadedScenes = new List <string>(); var inFirstUnloadedScenes = true; Scene firstLoadedScene = default(Scene); for (int i = 0; i < obj.sceneAssets.Count; i++) { var info = obj.sceneAssets[i]; if (info.asset == null) { continue; } var path = AssetDatabase.GetAssetPath(info.asset.GetInstanceID()); var mode = OpenSceneMode.Single; var isActiveScene = info.asset == obj.activeScene; var exitedFirstUnloadedScenes = false; if (inFirstUnloadedScenes) { if (!isActiveScene && !info.loadScene) { firstUnloadedScenes.Add(path); continue; } else { inFirstUnloadedScenes = false; exitedFirstUnloadedScenes = true; } } if ((!inFirstUnloadedScenes && !exitedFirstUnloadedScenes) || (additive && exitedFirstUnloadedScenes)) { if ((!additive && isActiveScene) || info.loadScene) { mode = OpenSceneMode.Additive; } else { mode = OpenSceneMode.AdditiveWithoutLoading; } } var scene = EditorSceneManager.OpenScene(path, mode); if (isActiveScene) { activeScene = scene; } if (exitedFirstUnloadedScenes) { firstLoadedScene = scene; } } for (int i = 0; i < firstUnloadedScenes.Count; i++) { var path = firstUnloadedScenes[i]; var scene = EditorSceneManager.OpenScene(path, OpenSceneMode.AdditiveWithoutLoading); if (firstLoadedScene.IsValid()) { EditorSceneManager.MoveSceneBefore(scene, firstLoadedScene); } } } if (!additive && activeScene.IsValid()) { EditorSceneManager.SetActiveScene(activeScene); } }
public Scene GetScene() { for (int i = 0; i < SceneManager.sceneCount; i++) { Scene scene = SceneManager.GetSceneAt(i); if (scene.name == name) { if (!scene.isLoaded) { if (Application.isPlaying) { EditorSceneManager.LoadSceneInPlayMode(scene.path, new LoadSceneParameters(LoadSceneMode.Additive)); } else { EditorSceneManager.OpenScene(scene.path, OpenSceneMode.Additive); } } return(scene); } } if (Application.isPlaying) { if (VerifyScene()) { EditorSceneManager.LoadSceneInPlayMode(GetScenePath(), new LoadSceneParameters(LoadSceneMode.Additive)); } else { Debug.Log("Creating temporary scene for data " + name + "."); SceneManager.CreateScene(name); } } else { Scene active = EditorSceneManager.GetActiveScene(); Lightmapping.bakedGI = false; Lightmapping.realtimeGI = false; if (VerifyScene()) { EditorSceneManager.OpenScene(GetScenePath(), OpenSceneMode.Additive); } else { Debug.Log("Recreating scene for data " + name + " in folder " + GetScenePath() + "."); EditorSceneManager.SaveScene(EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive), GetScenePath()); } EditorSceneManager.SetActiveScene(SceneManager.GetSceneByName(name)); Lightmapping.bakedGI = false; Lightmapping.realtimeGI = false; EditorSceneManager.SetActiveScene(active); } return(SceneManager.GetSceneByName(name)); bool VerifyScene() { string[] assets = AssetDatabase.FindAssets("t:Scene", new string[1] { GetDirectoryPath() }); if (assets.Length == 0) { return(false); } string path = AssetDatabase.GUIDToAssetPath(assets.First()); string id = path.Substring(path.LastIndexOf("/") + 1); id = id.Substring(0, id.LastIndexOf(".")); return(name == id); } }
private static void BuildPlayer(BuildTarget buildTarget) { CSObjectWrapEditor.Generator.ClearAll(); AssetDatabase.Refresh(); //gen xlua CSObjectWrapEditor.Generator.GenAll(); AssetDatabase.Refresh(); //设置场景的场景的参数 string launchScenePath = "Assets/Game/Scenes/main.unity"; UnityEngine.SceneManagement.Scene activeScene = EditorSceneManager.OpenScene(launchScenePath); if (activeScene != null) { EditorSceneManager.SetActiveScene(activeScene); foreach (var item in activeScene.GetRootGameObjects()) { if (item.name.Equals("GameMode")) { GameMode gameMode = item.GetComponent <GameMode>(); gameMode.ConfigJsonData["ResourceUpdateType"] = (int)ResourceUpdateType.Update; string configPath = AssetDatabase.GetAssetPath(gameMode.ConfigAsset); File.WriteAllText(configPath, gameMode.ConfigJsonData.ToJson()); AssetDatabase.Refresh(); EditorUtility.SetDirty(gameMode); EditorSceneManager.SaveOpenScenes(); AssetDatabase.Refresh(); break; } } } if (buildTarget == BuildTarget.Android) { //android keystore string path = Path.GetDirectoryName(Application.dataPath); string keyStorePath = Path.Combine(path, "tools/user.keystore"); PlayerSettings.Android.keystoreName = keyStorePath; PlayerSettings.Android.keystorePass = "******"; PlayerSettings.Android.keyaliasName = "********"; PlayerSettings.Android.keyaliasPass = "******"; } //build BuildPlayerOptions playerOptions = new BuildPlayerOptions(); playerOptions.scenes = EditorBuildSettingsScene.GetActiveSceneList(EditorBuildSettings.scenes); // playerOptions.scenes = new string[] { "Assets/Core/Scenes/SampleScene.unity" }; playerOptions.target = buildTarget; var buildTargetPath = $"build/{AssetBundleBuildEditor.BuildTargetToString(buildTarget)}"; if (!Directory.Exists(buildTargetPath)) { Directory.CreateDirectory(buildTargetPath); } if (buildTarget == BuildTarget.Android) { buildTargetPath = $"{buildTargetPath}/{Application.productName}.apk"; } else if (buildTarget == BuildTarget.StandaloneWindows) { buildTargetPath = $"{buildTargetPath}/{Application.productName}.exe"; } else if (buildTarget == BuildTarget.StandaloneLinux64) { buildTargetPath = $"{buildTargetPath}/{Application.productName}.x86_64"; } else if (buildTarget == BuildTarget.StandaloneOSX) { buildTargetPath = $"{buildTargetPath}/{Application.productName}"; } playerOptions.locationPathName = buildTargetPath; BuildPipeline.BuildPlayer(playerOptions); Debug.Log("build sccuess!"); }
public override void OnInspectorGUI() { serializedObject.Update(); var scene = serializedObject.FindProperty("scene"); var sceneAssetProperty = scene.FindPropertyRelative("sceneAssetObject"); EditorGUILayout.PropertyField(scene); if (sceneAssetProperty.objectReferenceValue != null) { var path = AssetDatabase.GetAssetPath(sceneAssetProperty.objectReferenceValue); var guid = AssetDatabase.AssetPathToGUID(path); var loadedScene = EditorSceneManager.GetSceneByPath(path); bool found = false; int index = 0; var buildScenes = EditorBuildSettings.scenes; for (int i = 0; i < buildScenes.Length; i++) { if (buildScenes [i].guid.ToString() == guid) { found = true; index = i; } } if (loadedScene.IsValid()) { if (EditorSceneManager.sceneCount > 1) { EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Close", GUILayout.Width(50))) { EditorSceneManager.CloseScene(loadedScene, true); } if (GUILayout.Button("Set Active", GUILayout.Width(100))) { EditorSceneManager.SetActiveScene(loadedScene); } EditorGUILayout.EndHorizontal(); } } else { if (GUILayout.Button("Open", GUILayout.Width(50))) { EditorSceneManager.OpenScene(path, OpenSceneMode.Additive); } } if (found) { if (GUILayout.Button("Remove scene from build", GUILayout.Width(170)) && EditorUtility.DisplayDialog("Remove Scene", "You sure you want to remove this scene from the build setting", "Yes", "Cancel")) { buildScenes = buildScenes.Remove(index); EditorBuildSettings.scenes = buildScenes; } } else { if (GUILayout.Button("Add Scene to build settings", GUILayout.Width(200))) { buildScenes = buildScenes.Add(new EditorBuildSettingsScene(path, true)); EditorBuildSettings.scenes = buildScenes; } } } }
/// <summary> /// Open scene and make it active. /// </summary> public void open_set_active() { EditorSceneManager.OpenScene(path); EditorSceneManager.SetActiveScene(EditorSceneManager.GetSceneByName(name)); }
//------------------------------------------------------------------------------------------------------------------------- // Determine which baking option is used // Then iterate through scene list to generate lighting and keep track of process private void BakeNewScene() { if (display == BakeOptions.Individual && !overrideLightSettings) { if (sceneIndex < scenes.Length) { EditorSceneManager.OpenScene(scenePath[sceneIndex], OpenSceneMode.Single); timeStamp = System.DateTime.Now; Lightmapping.BakeAsync(); UpdateLightmappingProcess(); sceneIndex++; } else { DoneLightmapping("done"); if (printTiming) { SaveOutputGrid(BakeLog); BakeLightmaps.Trace(" "); } } } else if (display == BakeOptions.Individual && overrideLightSettings && lightingPreset != null) { if (sceneIndex < scenes.Length) { EditorSceneManager.OpenScene(scenePath[sceneIndex], OpenSceneMode.Single); lightingPreset.Load(); timeStamp = System.DateTime.Now; Lightmapping.BakeAsync(); UpdateLightmappingProcess(); sceneIndex++; } else { DoneLightmapping("done"); if (printTiming) { SaveOutputGrid(BakeLog); BakeLightmaps.Trace(" "); } } } else if ((display == BakeOptions.Individual || display == BakeOptions.Group) && overrideLightSettings && lightingPreset == null) { UnityEngine.Debug.LogError("Please assign a Lighting Preset to override lighting settings for scenes"); } if (display == BakeOptions.Group && !overrideLightSettings) { Lightmapping.giWorkflowMode = Lightmapping.GIWorkflowMode.OnDemand; timeStamp = System.DateTime.Now; Lightmapping.BakeMultipleScenes(scenePath.ToArray()); UpdateLightmappingProcess(); } else if (display == BakeOptions.Group && overrideLightSettings && lightingPreset != null) { EditorSceneManager.OpenScene(scenePath[0], OpenSceneMode.Single); EditorSceneManager.SetActiveScene(EditorSceneManager.GetSceneByName(EditorSceneManager.GetActiveScene().name)); lightingPreset.Load(); Lightmapping.giWorkflowMode = Lightmapping.GIWorkflowMode.OnDemand; EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene()); timeStamp = System.DateTime.Now; Lightmapping.BakeMultipleScenes(scenePath.ToArray()); UpdateLightmappingProcess(); } }
public static void OpenLevel(GameLevel targetGameLevel, bool includeMasterScene, bool keepCurrentScenesThatAreOpenOpeneded, bool includeDependencies) { List <Scene> loadedScenes = new List <Scene>(); for (int i = 0; i < SceneManager.sceneCount; i++) { loadedScenes.Add(SceneManager.GetSceneAt(i)); } Scene[] loadedScenesArray = loadedScenes.ToArray(); EditorSceneManager.SaveModifiedScenesIfUserWantsTo(loadedScenesArray); //Load The Master Scene if (includeMasterScene == true) { string masterScenePath = "Assets/" + GameLevelToolkitWindow.GetProjectPathStringWithSlash() + "Scenes/" + SceneAndResourceFolderName.folderNameValue + "/Master Scene/Master Scene.unity"; Scene masterScene; if (keepCurrentScenesThatAreOpenOpeneded == true) { masterScene = EditorSceneManager.OpenScene(masterScenePath, OpenSceneMode.Additive); } else { masterScene = EditorSceneManager.OpenScene(masterScenePath, OpenSceneMode.Single); } EditorSceneManager.SetActiveScene(masterScene); } //Unload Any Existing Scenes If Required if (includeMasterScene == false && keepCurrentScenesThatAreOpenOpeneded == false) { for (int i = 0; i < SceneManager.sceneCount; i++) { Scene scene = SceneManager.GetSceneAt(i); if (!IsActiveScene(scene)) { CloseScene(scene); } if (scene.name == "Master Scene") { if (!IsActiveScene(scene)) { EditorSceneManager.SetActiveScene(scene); } } } } //Load The Locations Scenes LoadLocationsScenesAdditively(targetGameLevel); //Load Dependencies If Required if (includeDependencies == true) { for (int i = 0; i < targetGameLevel.levelDependencies.Count; i++) { LoadLocationsScenesAdditively(targetGameLevel.levelDependencies[i]); } } }
/*public static void OpenScenes(string name) * { * OCSceneConfig config = OCGenerator.GetSceneConfig(name); * string path = config.GetSceneAssetPath(); * path += "/"; * * * if (config.IsStreamScene) * { * int tileDim = config.TileDimension; * int tileSize = config.TileSize; * * var mainScene = SceneManager.GetSceneByName("AdditiveScene.unity"); * if(mainScene.isLoaded == false) * EditorSceneManager.OpenScene(path + "AdditiveScene.unity", OpenSceneMode.Additive); * * foreach (var index in config.indices) * { * string sceneName = string.Format("{0} {1}x{2}", name, index.x , index.y); * string scenePath = path + sceneName + ".unity"; * * var scene = SceneManager.GetSceneByName(sceneName); * if (scene.isLoaded == false) * EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive); * } * * } * else * { * EditorSceneManager.OpenScene(path + name +".unity"); * } * }*/ public static void GenerateTestStreamScenes(string name) { OCSceneConfig config = OCGenerator.GetSceneConfig(name); string path = config.GetSceneAssetPath(); path += "/"; int tileDim = config.TileDimension; int tileSize = config.TileSize; var template = Resources.Load("root") as GameObject; var mainScene = EditorSceneManager.OpenScene(path + "AdditiveScene.unity"); foreach (var root in mainScene.GetRootGameObjects()) { GameObject.DestroyImmediate(root); } var mainCamera = Resources.Load("MainCamera") as GameObject; var cam = GameObject.Instantiate(mainCamera); for (int i = 0; i < tileDim; i++) { for (int j = 0; j < tileDim; j++) { string sceneName = string.Format("{0} {1}x{2}", name, i, j); string scenePath = path + sceneName + ".unity"; var scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive); EditorSceneManager.SetActiveScene(scene); foreach (var root in scene.GetRootGameObjects()) { GameObject.DestroyImmediate(root); } var templateGO = GameObject.Instantiate(template); templateGO.transform.localScale = new Vector3(tileSize / 10, tileSize / 10, tileSize / 10); templateGO.transform.position = new Vector3(i * tileSize, 0, j * tileSize); var pos = templateGO.transform.position; float offsetValue = -tileSize * tileDim * 0.5f; Vector3 offset = new Vector3(offsetValue, 0, offsetValue); templateGO.transform.position = pos + offset; var coms = templateGO.GetComponentsInChildren <MeshRenderer>(); int count = 0; foreach (var com in coms) { var idcom = com.gameObject.GetComponent <GameObjectID>(); if (idcom == null) { idcom = com.gameObject.AddComponent <GameObjectID>(); } idcom.GUID = count; count++; } EditorSceneManager.SaveScene(scene); } } //EditorSceneManager.SaveOpenScenes(); }
private void CreateSceneEditObject() { bool focusObject = true; MeshHideAsset source = target as MeshHideAsset; if (source.asset == null) { return; } if (GeometrySelectorWindow.IsOpen) { return; } if (GeometrySelectorExists()) { GameObject.DestroyImmediate(GameObject.Find("GeometrySelector").gameObject); } bool hasDirtyScenes = false; for (int i = 0; i < EditorSceneManager.sceneCount; i++) { Scene sc = EditorSceneManager.GetSceneAt(i); if (sc.isDirty) { hasDirtyScenes = true; } } if (hasDirtyScenes) { int saveChoice = EditorUtility.DisplayDialogComplex("Modified scenes detected", "Opening the Mesh Hide Editor will close all scenes and create a new blank scene. Any current scene changes will be lost unless saved.", "Save and Continue", "Continue without saving", "Cancel"); switch (saveChoice) { case 0: // Save and continue { if (!EditorSceneManager.SaveOpenScenes()) { return; } break; } case 1: // don't save and continue break; case 2: // cancel return; } } SceneView sceneView = SceneView.lastActiveSceneView; if (sceneView == null) { EditorUtility.DisplayDialog("Error", "A Scene View must be open and active", "OK"); return; } SceneView.lastActiveSceneView.Focus(); List <GeometrySelector.SceneInfo> currentscenes = new List <GeometrySelector.SceneInfo>(); for (int i = 0; i < EditorSceneManager.sceneCount; i++) { Scene sc = EditorSceneManager.GetSceneAt(i); GeometrySelector.SceneInfo si = new GeometrySelector.SceneInfo(); si.path = sc.path; si.name = sc.name; if (i == 0) { // first scene should clear the temp scene. si.mode = OpenSceneMode.Single; } else { si.mode = sc.isLoaded ? OpenSceneMode.Additive : OpenSceneMode.AdditiveWithoutLoading; } currentscenes.Add(si); } #if UNITY_2019_1_OR_NEWER Scene s = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); #else Scene s = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single); #endif EditorSceneManager.SetActiveScene(s); GameObject obj = EditorUtility.CreateGameObjectWithHideFlags("GeometrySelector", HideFlags.DontSaveInEditor); GeometrySelector geometry = obj.AddComponent <GeometrySelector>(); // Restore the camera position. string CamKey = source.name + "_MHA_Cam"; if (EditorPrefs.HasKey(CamKey)) { string xform = EditorPrefs.GetString(CamKey); CamSaver cs = CamSaver.FromString(xform); sceneView.camera.transform.position = cs.position; sceneView.camera.transform.localRotation = cs.rotation; focusObject = false; } if (geometry != null) { Selection.activeGameObject = obj; if (focusObject) { SceneView.lastActiveSceneView.FrameSelected(true); } // sceneView.camera.transform; geometry.meshAsset = source; geometry.restoreScenes = currentscenes; geometry.currentSceneView = sceneView; #if UNITY_2019_1_OR_NEWER geometry.SceneviewLightingState = sceneView.sceneLighting; sceneView.sceneLighting = false; #else geometry.SceneviewLightingState = sceneView.m_SceneLighting; sceneView.m_SceneLighting = false; #endif geometry.InitializeFromMeshData(source.asset.meshData); geometry.selectedTriangles = new BitArray(source.triangleFlags[source.asset.subMeshIndex]); geometry.UpdateSelectionMesh(); if (focusObject) { SceneView.FrameLastActiveSceneView(); SceneView.lastActiveSceneView.FrameSelected(); } } }
void UpgradeMaterials() { // upgrade material template assets var assetList = new AssetList(); assetList.AddRange( AssetDatabase.FindAssets($"t:{nameof(PhysicsMaterialTemplate)}") .Select(guid => AssetDatabase.GUIDToAssetPath(guid)) .Select(path => new Asset(path)) ); if (assetList.Count > 0) { if (IsEditable(assetList, m_Failures)) { foreach (var asset in assetList) { if (!IsEditable(asset, m_Failures)) { continue; } // material templates are upgraded in OnEnable(), so it should be sufficient to merely load them var materialTemplate = AssetDatabase.LoadAssetAtPath <PhysicsMaterialTemplate>(asset.path); EditorUtility.SetDirty(materialTemplate); m_Successes.AddEntry(asset.path, string.Empty); } } } // upgrade prefabs assetList.Clear(); foreach (var guid in AssetDatabase.FindAssets("t:Prefab")) { var prefabAssetPath = AssetDatabase.GUIDToAssetPath(guid); var prefab = AssetDatabase.LoadAssetAtPath <GameObject>(prefabAssetPath); var shapeComponents = prefab.GetComponentsInChildren <PhysicsShapeAuthoring>(true); if (shapeComponents.Length == 0) { continue; } var asset = new Asset(prefabAssetPath); if (!IsEditable(asset, m_Failures)) { continue; } assetList.Add(asset); } if (assetList.Count > 0) { if (IsEditable(assetList, m_Failures)) { var upgradedAssets = new HashSet <Asset>(); foreach (var asset in assetList) { UpgradePrefabAsset(asset, assetList, upgradedAssets, m_Successes, m_Failures); } } } // update scene objects EditorSceneManager.SetActiveScene(EditorSceneManager.NewScene(NewSceneSetup.EmptyScene)); foreach (var guid in AssetDatabase.FindAssets("t:Scene")) { var scenePath = AssetDatabase.GUIDToAssetPath(guid); var asset = new Asset(scenePath); if (!IsEditable(asset, m_Failures)) { continue; } Scene scene; try { scene = EditorSceneManager.OpenScene(scenePath); } catch (Exception e) { m_Failures.AddEntry(asset.path, $"{e.Message}\n\n{e.StackTrace}"); continue; } EditorSceneManager.SetActiveScene(scene); var succcess = true; if (IsEditable(new AssetList { new Asset(scenePath) }, m_Failures)) { var upgradedAny = false; foreach ( var sceneObject in scene.GetRootGameObjects() .Where(go => go.GetComponentsInChildren <PhysicsShapeAuthoring>(true).Any()) ) { try { UpgradePrefabInstance(sceneObject); upgradedAny = true; } catch (Exception e) { succcess = false; m_Failures.AddEntry( $"{scenePath}::{AnimationUtility.CalculateTransformPath(sceneObject.transform, sceneObject.transform.root)}", $"{e.Message}\n\n{e.StackTrace}" ); } } if (upgradedAny) { EditorSceneManager.SaveScene(scene); } } if (succcess) { m_Successes.AddEntry(scenePath, string.Empty); } EditorSceneManager.SetActiveScene(EditorSceneManager.NewScene(NewSceneSetup.EmptyScene)); EditorSceneManager.CloseScene(scene, true); } }
public override void OnImportAsset(AssetImportContext ctx) { try { var sceneWithBuildConfiguration = SceneWithBuildConfigurationGUIDs.ReadFromFile(ctx.assetPath); // Ensure we have as many dependencies as possible registered early in case an exception is thrown EditorEntityScenes.AddEntityBinaryFileDependencies(ctx, sceneWithBuildConfiguration.BuildConfiguration); EditorEntityScenes.DependOnSceneGameObjects(sceneWithBuildConfiguration.SceneGUID, ctx); var config = BuildConfiguration.LoadAsset(sceneWithBuildConfiguration.BuildConfiguration); var scenePath = AssetDatabaseCompatibility.GuidToPath(sceneWithBuildConfiguration.SceneGUID); var scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive); try { EditorSceneManager.SetActiveScene(scene); var settings = new GameObjectConversionSettings(); settings.SceneGUID = sceneWithBuildConfiguration.SceneGUID; if (!sceneWithBuildConfiguration.IsBuildingForEditor) { settings.ConversionFlags |= GameObjectConversionUtility.ConversionFlags.IsBuildingForPlayer; } settings.BuildConfiguration = config; settings.AssetImportContext = ctx; settings.FilterFlags = WorldSystemFilterFlags.HybridGameObjectConversion; WriteEntitySceneSettings writeEntitySettings = new WriteEntitySceneSettings(); if (config != null && config.TryGetComponent <DotsRuntimeBuildProfile>(out var profile)) { if (config.TryGetComponent <DotsRuntimeRootAssembly>(out var rootAssembly)) { writeEntitySettings.Codec = Codec.LZ4; writeEntitySettings.IsDotsRuntime = true; writeEntitySettings.BuildAssemblyCache = new BuildAssemblyCache() { BaseAssemblies = rootAssembly.RootAssembly.asset, PlatformName = profile.Target.UnityPlatformName }; settings.FilterFlags = WorldSystemFilterFlags.DotsRuntimeGameObjectConversion; //Updating the root asmdef references or its references should re-trigger conversion ctx.DependsOnArtifact(AssetDatabase.GetAssetPath(rootAssembly.RootAssembly.asset)); foreach (var assemblyPath in writeEntitySettings.BuildAssemblyCache.AssembliesPath) { ctx.DependsOnArtifact(assemblyPath); } } } var sectionRefObjs = new List <ReferencedUnityObjects>(); var sectionData = EditorEntityScenes.ConvertAndWriteEntityScene(scene, settings, sectionRefObjs, writeEntitySettings); WriteAssetDependencyGUIDs(sectionRefObjs, sectionData, ctx); foreach (var objRefs in sectionRefObjs) { DestroyImmediate(objRefs); } } finally { EditorSceneManager.CloseScene(scene, true); } } // Currently it's not acceptable to let the asset database catch the exception since it will create a default asset without any dependencies // This means a reimport will not be triggered if the scene is subsequently modified catch (Exception e) { Debug.Log($"Exception thrown during SubScene import: {e}"); } }
/// <summary> /// Raises the GUI event. /// </summary> void OnGUI() { if (!string.IsNullOrEmpty(warning)) { GUILayout.Space(20); var TextStyle = new GUIStyle(); TextStyle.normal.textColor = Color.red; TextStyle.alignment = TextAnchor.MiddleCenter; TextStyle.fontStyle = FontStyle.Bold; GUILayout.Label(warning, TextStyle); } scrollPos = EditorGUILayout.BeginScrollView(scrollPos); EditorGUIUtility.wideMode = true; collectionsCollapsed = EditorGUILayout.Foldout(collectionsCollapsed, "Scene collections: "); if (collectionsCollapsed) { EditorGUI.indentLevel++; listSizeCollections = EditorGUILayout.IntField("size", listSizeCollections); if (listSizeCollections != currentCollections.Count) { while (listSizeCollections > currentCollections.Count) { currentCollections.Add(null); } while (listSizeCollections < currentCollections.Count) { currentCollections.RemoveAt(currentCollections.Count - 1); } } for (int i = 0; i < currentCollections.Count; i++) { currentCollections [i] = (SceneCollection)EditorGUILayout.ObjectField(currentCollections [i], typeof(SceneCollection), true); } EditorGUI.indentLevel--; } GUILayout.Space(10); distanceFromCenter = EditorGUILayout.IntField("Loading distance", distanceFromCenter); if (distanceFromCenter < 0) { distanceFromCenter = 0; } EditorGUILayout.BeginHorizontal(); tiles = EditorGUILayout.Toggle("Tiles", tiles); tiles = !EditorGUILayout.Toggle("Units", !tiles); EditorGUILayout.EndHorizontal(); GUILayout.Space(10); CenterPoint = EditorGUILayout.Vector3Field("Loading Center", CenterPoint); EditorGUILayout.BeginHorizontal(); showLoadingPoint = EditorGUILayout.Toggle("Show loading center", showLoadingPoint); if (GUILayout.Button("Show center")) { if (SceneView.lastActiveSceneView != null) { SceneView.lastActiveSceneView.LookAt(CenterPoint); } } EditorGUILayout.EndHorizontal(); GUILayout.Space(10); GUILayout.Space(10); if (GUILayout.Button("Load Scenes from Collections around Center Point")) { LoadScenesAroundCenterPoint(); } if (GUILayout.Button("Load All Scenes from Collections")) { LoadScenes(); } GUILayout.Space(10); if (GUILayout.Button("Unsplit Scenes")) { foreach (var sceneCollection in currentCollections) { splits.Add(new Dictionary <string, GameObject> ()); UnSplitScene(sceneCollection); } } if (GUILayout.Button("Split Scenes")) { UnityEngine.SceneManagement.Scene scene = EditorSceneManager.GetActiveScene(); if (!scene.isDirty || EditorUtility.DisplayDialog("Save warning", "For spliting Your active scene must be saved!", "Save active scene now", "No") && EditorSceneManager.SaveScene(scene)) { splits = new List <Dictionary <string, GameObject> > (); foreach (var sceneCollection in currentCollections) { splits.Add(new Dictionary <string, GameObject> ()); SplitScene(sceneCollection); } EditorSceneManager.MarkAllScenesDirty(); EditorSceneManager.SetActiveScene(scene); } } GUILayout.Space(10); if (GUILayout.Button("Save loaded Scenes")) { SaveScenes(); } if (GUILayout.Button("Unload loaded Scenes")) { UnloadScenes(); } GUILayout.Space(10); if (GUILayout.Button("Remove empty Scenes from collections")) { RemoveEmptyScenes(); } if (GUILayout.Button("Delete empty Scenes")) { if (EditorUtility.DisplayDialog("Delete warning", "Do You want do delete scene files from project folder. This operation can't be undone", "Yes, I want do delete scene files", "No")) { RemoveEmptyScenes(true); } } EditorGUILayout.EndScrollView(); }
private void DrawLeftSceneSection(Rect leftDataArea) { if (selectedScene && showRightPanel == false) { var path = AssetDatabase.GetAssetPath(selectedScene); var scene = EditorSceneManager.OpenScene(path, OpenSceneMode.Additive); if (scene.IsValid() && scene.isLoaded) { // Right Panel showRightPanel = true; rightPanelTitle = "Scene: \"" + scene.path + "\" Statistics"; } } EditorGUILayout.Space(); float y = 0; float singleH = 55; float h = scenes.Count * 1 * singleH; float nh = leftDataArea.height; float nw = leftDataArea.width; if (leftDataArea.height < h) { float dt = Mathf.Abs(leftDataArea.height - (h)); nh += dt; nw -= 25; } else { nh -= 15; nw -= 8; } GUILayout.Label("", GUILayout.Width(leftDataArea.width - 29), GUILayout.Height(nh)); for (int i = 0; i < scenes.Count * 1; i++) { GUILayout.BeginArea(new Rect(0, y, nw, 55), EditorStyles.helpBox); GUILayout.Space(3); EditorGUILayout.BeginHorizontal(); GUILayout.Label(scenes[i].name, EditorStyles.label, GUILayout.Width(leftDataArea.width / 3 - 15)); scenes[i] = (SceneAsset)EditorGUILayout.ObjectField(scenes[i], typeof(SceneAsset), false, GUILayout.Width((leftDataArea.width * 2 / 3) - 37)); if (GUILayout.Button("X", EditorStyles.toolbarButton)) { toBeDeletedScene = scenes[i]; } EditorGUILayout.EndHorizontal(); GUILayout.Space(3); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Open and Show Details")) { var path = AssetDatabase.GetAssetPath(scenes[i]); var scene = EditorSceneManager.OpenScene(path, OpenSceneMode.Additive); if (scene.IsValid() && scene.isLoaded) { // Right Panel showRightPanel = true; selectedScene = scenes[i]; rightPanelTitle = "Scene: \"" + scene.path + "\" Statistics"; } } GUILayout.Space(2); if (GUILayout.Button("Make Active")) { var path = AssetDatabase.GetAssetPath(scenes[i]); var scene = EditorSceneManager.OpenScene(path, OpenSceneMode.Additive); if (scene.IsValid() && scene.isLoaded) { EditorSceneManager.SetActiveScene(scene); } } GUILayout.Space(2); if (GUILayout.Button("CloseScene")) { var path = AssetDatabase.GetAssetPath(scenes[i]); var scene = EditorSceneManager.GetSceneByPath(path); selectedScene = null; showRightPanel = false; rightPanelTitle = ""; if (scene.IsValid() && scene.isLoaded) { EditorSceneManager.SaveScene(scene); } if (scene.IsValid()) { EditorSceneManager.CloseScene(scene, true); } } EditorGUILayout.EndHorizontal(); GUILayout.EndArea(); y += 65; } }
public static void Create() { Scene scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); EditorSceneManager.SetActiveScene(scene); GameObject root = new GameObject("LevelRoot"); root.transform.position = Vector3.left * 0.5f; AddComponent <Grid>(root); AddComponent <Layers>(root); Material pixelArtSprite = AssetDatabase.LoadAssetAtPath <Material>("Assets/Plugins/PixelArtCamera/PixelArtSprite.mat"); GameObject floor = CreateGO("Floor", root); AddComponent <Tilemap>(floor, SetTilemap); AddComponent <TilemapRenderer>(floor, tr => { tr.sortingOrder = 0; tr.material = pixelArtSprite; }); GameObject spawnPointsPlayer = CreateGO("SpawnPointsPlayers", root); spawnPointsPlayer.layer = LayerMask.NameToLayer("Obstacles"); AddComponent <Tilemap>(spawnPointsPlayer, SetTilemap); AddComponent <TilemapRenderer>(spawnPointsPlayer, tr => { tr.sortingOrder = 1; tr.material = pixelArtSprite; }); GameObject spawnPointsTurrets = CreateGO("SpawnPointsTurrets", root); spawnPointsTurrets.layer = LayerMask.NameToLayer("Obstacles"); AddComponent <Tilemap>(spawnPointsTurrets, SetTilemap); AddComponent <TilemapRenderer>(spawnPointsTurrets, tr => { tr.sortingOrder = 1; tr.material = pixelArtSprite; }); GameObject walls = CreateGO("Walls", root); walls.layer = LayerMask.NameToLayer("Walls"); AddComponent <Tilemap>(walls, SetTilemap); AddComponent <TilemapRenderer>(walls, tr => { tr.sortingOrder = 2; tr.material = pixelArtSprite; }); AddComponent <TilemapCollider2D>(walls, tc => { tc.usedByComposite = true; }); AddComponent <Rigidbody2D>(walls, rb => { rb.bodyType = RigidbodyType2D.Static; rb.simulated = true; }); AddComponent <CompositeCollider2D>(walls, cc => { cc.isTrigger = false; cc.usedByEffector = false; cc.offset = Vector2.zero; cc.geometryType = CompositeCollider2D.GeometryType.Outlines; cc.generationType = CompositeCollider2D.GenerationType.Synchronous; }); GameObject obstacles = CreateGO("Obstacles", root); obstacles.layer = LayerMask.NameToLayer("Obstacles"); AddComponent <Tilemap>(obstacles, SetTilemap); AddComponent <TilemapRenderer>(obstacles, tr => { tr.sortingOrder = 3; tr.material = pixelArtSprite; }); AddComponent <TilemapCollider2D>(obstacles, tc => { tc.usedByComposite = false; tc.isTrigger = true; tc.usedByEffector = false; }); AddComponent <Hurt>(obstacles); GameObject projectileKiller = CreateGO("ProjectileKiller", root); projectileKiller.layer = LayerMask.NameToLayer("Killer"); AddComponent <Tilemap>(projectileKiller, SetTilemap); AddComponent <TilemapRenderer>(projectileKiller, tr => { tr.sortingOrder = 2; tr.material = pixelArtSprite; }); AddComponent <TilemapCollider2D>(projectileKiller, tc => { tc.usedByComposite = true; }); AddComponent <Rigidbody2D>(projectileKiller, rb => { rb.bodyType = RigidbodyType2D.Static; rb.simulated = true; }); AddComponent <CompositeCollider2D>(projectileKiller, cc => { cc.isTrigger = true; cc.usedByEffector = false; cc.offset = Vector2.zero; cc.geometryType = CompositeCollider2D.GeometryType.Outlines; cc.generationType = CompositeCollider2D.GenerationType.Synchronous; }); }
protected void SetSceneToActive(Scene scene) { EditorSceneManager.SetActiveScene(scene); }
public override void OnImportAsset(AssetImportContext ctx) { try { ctx.DependsOnCustomDependency("EntityBinaryFileFormatVersion"); ctx.DependsOnCustomDependency("SceneMetaDataFileFormatVersion"); ctx.DependsOnSourceAsset(EntitiesCacheUtility.globalEntitySceneDependencyPath); var sceneWithBuildConfiguration = SceneWithBuildConfigurationGUIDs.ReadFromFile(ctx.assetPath); // Ensure we have as many dependencies as possible registered early in case an exception is thrown var scenePath = AssetDatabase.GUIDToAssetPath(sceneWithBuildConfiguration.SceneGUID.ToString()); ctx.DependsOnSourceAsset(scenePath); if (sceneWithBuildConfiguration.BuildConfiguration.IsValid) { var buildConfigurationPath = AssetDatabase.GUIDToAssetPath(sceneWithBuildConfiguration.BuildConfiguration.ToString()); ctx.DependsOnSourceAsset(buildConfigurationPath); var buildConfigurationDependencies = AssetDatabase.GetDependencies(buildConfigurationPath); foreach (var dependency in buildConfigurationDependencies) { ctx.DependsOnSourceAsset(dependency); } } var dependencies = AssetDatabase.GetDependencies(scenePath); foreach (var dependency in dependencies) { if (dependency.ToLower().EndsWith(".prefab")) { ctx.DependsOnSourceAsset(dependency); } } var config = BuildConfiguration.LoadAsset(sceneWithBuildConfiguration.BuildConfiguration); var scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive); try { var settings = new GameObjectConversionSettings(); settings.SceneGUID = sceneWithBuildConfiguration.SceneGUID; settings.BuildConfiguration = config; settings.AssetImportContext = ctx; settings.FilterFlags = WorldSystemFilterFlags.HybridGameObjectConversion; WriteEntitySceneSettings writeEntitySettings = new WriteEntitySceneSettings(); if (config != null && config.TryGetComponent <DotsRuntimeBuildProfile>(out var profile)) { if (config.TryGetComponent <DotsRuntimeRootAssembly>(out var rootAssembly)) { ctx.DependsOnSourceAsset(AssetDatabase.GetAssetPath(rootAssembly.RootAssembly.asset)); EditorSceneManager.SetActiveScene(scene); writeEntitySettings.Codec = Codec.LZ4; writeEntitySettings.IsDotsRuntime = true; writeEntitySettings.BuildAssemblyCache = new BuildAssemblyCache() { BaseAssemblies = rootAssembly.RootAssembly.asset, PlatformName = profile.Target.UnityPlatformName }; settings.FilterFlags = WorldSystemFilterFlags.DotsRuntimeGameObjectConversion; } } var sectionRefObjs = new List <ReferencedUnityObjects>(); var sectionData = EditorEntityScenes.ConvertAndWriteEntitySceneInternal(scene, settings, sectionRefObjs, writeEntitySettings); WriteAssetDependencyGUIDs(sectionRefObjs, sectionData, ctx); } finally { EditorSceneManager.CloseScene(scene, true); } } // Currently it's not acceptable to let the asset database catch the exception since it will create a default asset without any dependencies // This means a reimport will not be triggered if the scene is subsequently modified catch (Exception e) { Debug.Log($"Exception thrown during SubScene import: {e}"); } }
public void FindAllReferences(List <string> scenes) { References = new List <EventReference>(); if (scenes.Count > 0) { var activeScene = EditorSceneManager.GetActiveScene(); for (int i = 0; i < EditorSceneManager.sceneCount; i++) { if (EditorSceneManager.GetSceneAt(i) != activeScene && EditorSceneManager.GetSceneAt(i).isLoaded) { if (EditorSceneManager.GetSceneAt(i).isLoaded) { EditorSceneManager.SaveScene(EditorSceneManager.GetSceneAt(i)); } else { EditorSceneManager.LoadScene(EditorSceneManager.GetSceneAt(i).path, LoadSceneMode.Additive); } EditorSceneManager.SetActiveScene(activeScene); } } for (int i = 0; i < scenes.Count; i++) { for (int j = 0; j < _Scenes.Count; j++) { { var guid1 = AssetDatabase.AssetPathToGUID(scenes[i]); var guid2 = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(_Scenes[j])); if (guid1.Equals(guid2)) { var scene = EditorSceneManager.OpenScene(scenes[i], OpenSceneMode.Additive); { if (scene.IsValid() && scene.isLoaded) { var allObjects = scene.GetRootGameObjects(); for (int k = 0; k < allObjects.Length; k++) { var obj = allObjects[k]; var comps = obj.GetComponentsInChildren <MonoBehaviour>(true); foreach (var comp in comps) { FieldInfo[] fields = comp.GetType().GetFields(); var eventReference = new EventReference(); eventReference.Reference = comp; bool add = false; foreach (var field in fields) { KAIEvent attrib = Attribute.GetCustomAttribute(field, typeof(KAIEvent)) as KAIEvent; if (attrib != null) { eventReference.Events.Add(field.GetValue(comp) as CustomEvent); eventReference.ReferenceNames.Add(field.Name); eventReference.Fields.Add(field); add = true; } } if (add) { References.Add(eventReference); } } } } } } } } } } }
/// <summary> /// 创建Asset,请调用前确保没有重名Asset /// </summary> public static void CreateGroupAsset(MapGroup group) { string groupName = group.groupName; string path = AssetPath + groupName + "/" + groupName; int index = group.index; //创建Asset MapGroupAsset asset = ScriptableObject.CreateInstance <MapGroupAsset>(); asset.groupName = groupName; AssetDatabase.CreateFolder("Assets/Scenes/GroupAssets", groupName); //初始化 group.transform.position = Vector3.zero; group.index = -1; group.transform.rotation = Quaternion.identity; bool isRootOfScene = group.transform.parent == null; group.transform.SetParent(null); //绑定Prefab asset.groupPrefab = PrefabUtility.CreatePrefab(path + ".prefab", group.gameObject, ReplacePrefabOptions.ConnectToPrefab); //创建场景 Scene activeScene = EditorSceneManager.GetActiveScene(); Scene scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); EditorSceneManager.SetActiveScene(activeScene); Scene oldScene = group.gameObject.scene; EditorSceneManager.MoveGameObjectToScene(group.gameObject, scene); if (isRootOfScene) { EditorSceneManager.CloseScene(oldScene, true); } //保存场景 //这里path的命名不是很懂,scene居然不能直接改名? { EditorSceneManager.SaveScene(scene, path + "0.unity"); group.transform.rotation = Quaternion.Euler(0, -MapSystem.AnglePerGroup, 0); PrefabUtility.RecordPrefabInstancePropertyModifications(group.transform); EditorSceneManager.SaveScene(scene, path + "1.unity"); group.transform.rotation = Quaternion.Euler(0, -MapSystem.AnglePerGroup * 2, 0); PrefabUtility.RecordPrefabInstancePropertyModifications(group.transform); EditorSceneManager.SaveScene(scene, path + "2.unity"); } //重新载入 EditorSceneManager.CloseScene(scene, true); LoadGroupDirect(asset, index); //保存 AssetDatabase.CreateAsset(asset, AssetPath + groupName + ".asset"); MapGroupAssets.Add(asset); EditorUtility.SetDirty(EditorMatrix.Prefs); }
public override object GetSource(ValidationProfileResult entry) { if (entry.Source as UnityEngine.Object) { return(entry.Source); } var address = (SceneAddress)entry.SourceRecoveryData; // This should work. bool openScene = true; foreach (var setupScene in EditorSceneManager.GetSceneManagerSetup()) { if (setupScene.path == address.ScenePath) { openScene = false; if (!setupScene.isActive) { EditorSceneManager.SetActiveScene(EditorSceneManager.GetSceneByPath(setupScene.path)); } break; } } if (openScene) { if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { return(null); } EditorSceneManager.OpenScene(address.ScenePath, OpenSceneMode.Single); } var go = this.GetGameObjectFromIndexPath(address); if (go != null) { entry.Source = go; if (address.ComponentType != null) { Component component = null; var components = go.GetComponents(address.ComponentType); if (address.ComponentIndex >= 0 && address.ComponentIndex < components.Length) { component = components[address.ComponentIndex]; } if (component != null) { entry.Source = component; } } } return(entry.Source); }
static void SetSceneActive(object userData) { Scene scene = (Scene)userData; EditorSceneManager.SetActiveScene(scene); }
private static void Build(BuildTarget target) { if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { return; } string[] scenePaths = EditorBuildSettings.scenes .Where(s => s.enabled) .Select(s => s.path) .ToArray(); if (scenePaths.Count() == 0) { EditorUtility.DisplayDialog("Error", "Add or enable scenes to be included in the Build Settings menu.", "Ok"); return; } Patcher.Patcher patcher = null; foreach (var scenePath in scenePaths) { var scene = EditorSceneManager.OpenScene(scenePath); EditorSceneManager.SetActiveScene(scene); patcher = PatchKit.Unity.Patcher.Patcher.Instance; if (patcher) { break; } } if (!patcher) { EditorUtility.DisplayDialog("Error", "Couldn't resolve an instance of the Patcher component in any of the build scenes.", "Ok"); return; } if (patcher.EditorAppSecret != PatchKit.Unity.Patcher.Patcher.EditorAllowedSecret) { if (EditorUtility.DisplayDialog("Error", "Please reset the editor app secret to continue building.", "Reset the secret and continue", "Cancel")) { patcher.EditorAppSecret = PatchKit.Unity.Patcher.Patcher.EditorAllowedSecret; var activeScene = EditorSceneManager.GetActiveScene(); EditorSceneManager.MarkSceneDirty(activeScene); EditorSceneManager.SaveScene(activeScene); } else { return; } } BuildOptions buildOptions = BuildOptions.ForceEnableAssertions | BuildOptions.ShowBuiltPlayer; string path = EditorUtility.SaveFolderPanel("Choose where to build the Patcher", "", ""); if (string.IsNullOrEmpty(path)) { return; } string error = BuildPipeline.BuildPlayer(scenePaths, path + "/" + PatcherExecutableName(target), target, buildOptions); if (!string.IsNullOrEmpty(error)) { EditorUtility.DisplayDialog("Error", error, "Ok"); } }
public static void EditorLoadScenePackage(this ScriptableScenePackage scriptableScenePackage, bool askSaveToUser = true, bool removeScene = true) { if (askSaveToUser) { EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); } EditorApplication.isPaused = false; EditorApplication.isPlaying = false; for (int i = 0; i < scriptableScenePackage.startScenePackages.Length; i++) { scriptableScenePackage.startScenePackages[i].EditorLoadScenePackage(false, false); } SceneAsset[] sceneAssets = FindAssetExtension.GetAllInstances <SceneAsset>(); for (int i = 0; i < scriptableScenePackage.scenes.Length; i++) { Scene s = EditorSceneManager.GetSceneByName(scriptableScenePackage.scenes[i]); if (!s.isLoaded) { EditorSceneManager.OpenScene(AssetDatabase.GetAssetPath(Array.Find(sceneAssets, (x) => { return(x.name == scriptableScenePackage.scenes[i]); })), OpenSceneMode.Additive); } EditorSceneManager.SetActiveScene(EditorSceneManager.GetSceneByName(scriptableScenePackage.scenes[i])); } for (int i = 0; i < scriptableScenePackage.cheatScenes.Length; i++) { Scene s = EditorSceneManager.GetSceneByName(scriptableScenePackage.cheatScenes[i]); if (!s.isLoaded) { EditorSceneManager.OpenScene(AssetDatabase.GetAssetPath(Array.Find(sceneAssets, (x) => { return(x.name == scriptableScenePackage.cheatScenes[i]); })), OpenSceneMode.Additive); } } for (int i = 0; i < scriptableScenePackage.endScenePackages.Length; i++) { scriptableScenePackage.endScenePackages[i].EditorLoadScenePackage(false, false); } if (removeScene) { for (int i = EditorSceneManager.sceneCount - 1; i >= 0; i--) { Scene s = EditorSceneManager.GetSceneAt(i); if (ScriptableScenePackage.SceneHasToBeRemoved(scriptableScenePackage, s.name)) { EditorSceneManager.CloseScene(s, true); } } } if (!String.IsNullOrEmpty(scriptableScenePackage.activeScene) && EditorSceneManager.GetSceneByName(scriptableScenePackage.activeScene).IsValid()) { EditorSceneManager.SetActiveScene(EditorSceneManager.GetSceneByName(scriptableScenePackage.activeScene)); } }
public IEnumerator LodSplitOverSections() { var guid = GUID.Generate(); var temp = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene); EditorSceneManager.SetActiveScene(temp); // Large set of dummy entities to stress the public ref array const int dummyCount = 100; for (int i = 0; i < dummyCount; ++i) { new GameObject($"Dummy {i}"); } var lod0Renderer = GameObject.CreatePrimitive(PrimitiveType.Cube); var lod1Renderer = GameObject.CreatePrimitive(PrimitiveType.Cube); var lod2Renderer = GameObject.CreatePrimitive(PrimitiveType.Cube); lod0Renderer.transform.position = new Vector3(0, 0, 0); lod1Renderer.transform.position = new Vector3(1, 0, 0); lod2Renderer.transform.position = new Vector3(2, 0, 0); var highLod = new GameObject("HighLOD"); highLod.SetActive(false); var highLodGroup = highLod.AddComponent <LODGroup>(); var lowLod = new GameObject("LowLOD"); lowLod.SetActive(false); var lowLodGroup = lowLod.AddComponent <LODGroup>(); var hlod = new GameObject("HLOD"); hlod.SetActive(false); var hlodComponent = hlod.AddComponent <HLOD>(); var hlodGroup = hlod.GetComponent <LODGroup>(); lod0Renderer.transform.parent = highLod.transform; lod1Renderer.transform.parent = highLod.transform; lod2Renderer.transform.parent = lowLod.transform; highLod.transform.parent = hlod.transform; lowLod.transform.parent = hlod.transform; highLodGroup.SetLODs(new[] { new LOD(0.75f, new[] { lod0Renderer.GetComponent <Renderer>() }), new LOD(0.00f, new[] { lod1Renderer.GetComponent <Renderer>() }), }); lowLodGroup.SetLODs(new[] { new LOD(0.00f, new[] { lod2Renderer.GetComponent <Renderer>() }), }); hlodComponent.LODParentTransforms = new[] { highLod.transform, lowLod.transform }; hlodGroup.SetLODs(new[] { new LOD(0.25f, new Renderer[] {}), new LOD(0.00f, new Renderer[] {}), }); highLod.SetActive(true); lowLod.SetActive(true); hlod.SetActive(true); var entitySceneData = EditorEntityScenes.WriteEntityScene(temp, guid, 0); Assert.AreEqual(2, entitySceneData.Length); var sceneEntitySection0 = m_Manager.CreateEntity(); m_Manager.AddComponentData(sceneEntitySection0, entitySceneData[0]); var sceneEntitySection1 = m_Manager.CreateEntity(); m_Manager.AddComponentData(sceneEntitySection1, entitySceneData[1]); // Loading one scene at a time for (int i = 0; i != 10; i++) { Assert.AreEqual(2, m_Manager.Debug.EntityCount); m_Manager.AddComponentData(sceneEntitySection0, new RequestSceneLoaded()); for (int w = 0; w != 1000; w++) { World.GetOrCreateSystem <SubSceneStreamingSystem>().Update(); if (2 != m_Manager.Debug.EntityCount) { break; } Assert.AreNotEqual(999, w, "Streaming is stuck"); yield return(null); } // 1. Scene entity section 0 // 2. Scene entity section 1 // 3. Public ref array // 4. HLOD // 5. LowLod group // 6. LOD2 renderer Assert.AreEqual(dummyCount + 6, m_Manager.Debug.EntityCount); // Destroying and recreating the system causes the streaming worlds to reset, otherwise oversize // buffers could carry over and would not trigger the right asserts. World.DestroySystem(World.GetExistingSystem <SubSceneStreamingSystem>()); m_Manager.AddComponentData(sceneEntitySection1, new RequestSceneLoaded()); for (int w = 0; w != 1000; w++) { World.GetOrCreateSystem <SubSceneStreamingSystem>().Update(); if (dummyCount + 6 != m_Manager.Debug.EntityCount) { break; } Assert.AreNotEqual(999, w, "Streaming is stuck"); yield return(null); } // 1. Scene entity section 0 // 2. Scene entity section 1 // 3. Public ref array // 4. HLOD // 5. LowLod group // 6. LOD2 renderer // 7. External ref array // 8. HighLod group // 9. LOD1 renderer // A. LOD0 renderer Assert.AreEqual(dummyCount + 10, m_Manager.Debug.EntityCount); m_Manager.RemoveComponent <RequestSceneLoaded>(sceneEntitySection1); World.GetOrCreateSystem <SubSceneStreamingSystem>().Update(); Assert.AreEqual(dummyCount + 6, m_Manager.Debug.EntityCount); m_Manager.RemoveComponent <RequestSceneLoaded>(sceneEntitySection0); World.GetOrCreateSystem <SubSceneStreamingSystem>().Update(); Assert.AreEqual(2, m_Manager.Debug.EntityCount); } }
void LoadDefaultPlayerPosition() { #if !UNITY_EDITOR return; #endif if (!defaultPlayerPosition || hasLoadedDefaultPlayerPosition) { return; } string sceneName = GetSceneName(); string positionKey = $"{PositionKeyPrefix}.{sceneName}"; string rotationKey = $"{RotationKeyPrefix}.{sceneName}"; string edgeDetectionKey = $"{EdgeDetectionSettingsKeyPrefix}.{sceneName}"; if (HasVector3(positionKey) && HasVector3(rotationKey)) { Vector3 pos = GetVector3(positionKey); Vector3 eulerRot = GetVector3(rotationKey); Player.instance.transform.position = pos; Player.instance.transform.rotation = Quaternion.Euler(eulerRot); } if (PlayerPrefs.HasKey(edgeDetectionKey)) { Camera mainCam = GameObject.Find("Main Camera")?.GetComponent <Camera>(); BladeEdgeDetection edgeDetection = (mainCam == null) ? null : mainCam.GetComponent <BladeEdgeDetection>(); if (edgeDetection != null) { GetEDSettings(edgeDetectionKey).ApplyTo(edgeDetection); } } if (DEBUG) { if (!HasVector3(positionKey)) { Debug.LogError($"No position key found for {positionKey}"); } if (!HasVector3(rotationKey)) { Debug.LogError($"No rotation key found for {rotationKey}"); } } // Hijacking this to display level banner on load, even when it's already the active scene LevelChangeBanner.instance.PlayBanner(enumToSceneName[sceneName]); #if UNITY_EDITOR try { Scene scene = EditorSceneManager.GetSceneByName(sceneName); if (!EditorSceneManager.GetSceneByName(sceneName).IsValid()) { string path = $"Assets/{(sceneName != enumToSceneName[Levels.TestScene] ? "__Scenes" : "PrototypeAndTesting")}/{sceneName}.unity"; scene = EditorSceneManager.OpenScene(path, OpenSceneMode.Additive); } EditorSceneManager.SetActiveScene(scene); } catch (Exception e) { Debug.LogError(e); } if (EditorApplication.isPlaying) #endif hasLoadedDefaultPlayerPosition = true; }
private void CreateSceneEditObject() { MeshHideAsset source = target as MeshHideAsset; if (source.asset == null) { return; } if (GeometrySelectorWindow.IsOpen) { return; } if (GeometrySelectorExists()) { GameObject.DestroyImmediate(GameObject.Find("GeometrySelector").gameObject); } int saveChoice = EditorUtility.DisplayDialogComplex("Open Mesh Hide Editor", "Opening the Mesh Hide Editor will close all scenes and create a new blank scene. Any current scene changes will be lost unless saved.", "Save and Continue", "Continue without saving", "Cancel"); switch (saveChoice) { case 0: // Save and continue { if (!EditorSceneManager.SaveOpenScenes()) { return; } break; } case 1: // don't save and continue break; case 2: // cancel return; } SceneView sceneView = SceneView.lastActiveSceneView; if (sceneView == null) { EditorUtility.DisplayDialog("Error", "A Scene View must be open and active", "OK"); return; } SceneView.lastActiveSceneView.Focus(); List <GeometrySelector.SceneInfo> currentscenes = new List <GeometrySelector.SceneInfo>(); for (int i = 0; i < EditorSceneManager.sceneCount; i++) { Scene sc = EditorSceneManager.GetSceneAt(i); GeometrySelector.SceneInfo si = new GeometrySelector.SceneInfo(); si.path = sc.path; si.name = sc.name; if (i == 0) { // first scene should clear the temp scene. si.mode = OpenSceneMode.Single; } else { si.mode = sc.isLoaded ? OpenSceneMode.Additive : OpenSceneMode.AdditiveWithoutLoading; } currentscenes.Add(si); } Scene s = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single); EditorSceneManager.SetActiveScene(s); GameObject obj = EditorUtility.CreateGameObjectWithHideFlags("GeometrySelector", HideFlags.DontSaveInEditor); GeometrySelector geometry = obj.AddComponent <GeometrySelector>(); if (geometry != null) { Selection.activeGameObject = obj; SceneView.lastActiveSceneView.FrameSelected(true); geometry.meshAsset = source; geometry.restoreScenes = currentscenes; geometry.InitializeFromMeshData(source.asset.meshData); //temporary, only works on submesh 0 geometry.selectedTriangles = new BitArray(source.triangleFlags[0]); geometry.UpdateSelectionMesh(); SceneView.FrameLastActiveSceneView(); SceneView.lastActiveSceneView.FrameSelected(); } }
public static void Generate() { if (Application.isPlaying) { return; } const string title = "Generating propery accessors"; EditorUtility.DisplayProgressBar(title, "", 0); #if UNITY_5_3_OR_NEWER var currentLevel = EditorSceneManager.GetActiveScene(); #else var currentLevel = EditorApplication.currentScene; #endif _contents = new StringBuilder(); _paths.Clear(); EditorUtility.DisplayProgressBar(title, "Creating header", 0); CreateHeader(_contents); var scenes = SelectedScenes; float total = scenes.Length + 1; for (int i = 0; i < scenes.Length; i++) { var level = scenes[i]; EditorUtility.DisplayProgressBar(title, "Opening scene " + level, i / total); #if UNITY_5_3_OR_NEWER var scene = EditorSceneManager.OpenScene(level); EditorSceneManager.SetActiveScene(scene); #else EditorApplication.OpenScene(level); #endif EditorUtility.DisplayProgressBar(title, "Adding paths in " + level, i / total); BuildPathsInScene(_contents); #if UNITY_5_3_OR_NEWER EditorSceneManager.CloseScene(scene, true); #endif } EditorUtility.DisplayProgressBar(title, "Generating for prefabs", total - 0.5f / total); GenForPrefabs(_contents); FinishContents(_contents); EditorUtility.DisplayProgressBar(title, "Reopening original", 1); #if UNITY_5_3_OR_NEWER EditorSceneManager.SetActiveScene(currentLevel); #endif var contents = _contents.ToString(); if (!ValidateContents(contents)) { var sw = new StreamWriter(CreateFile()); sw.Write(contents); FinishFile(sw); AssetDatabase.ImportAsset(_filePath.Replace(Application.dataPath, "Assets")); } ClearState(); EditorUtility.ClearProgressBar(); }