void OnGUI() { if (isHide) { if (GUILayout.Button("Unhide")) { isHide = false; } } if (isHide) { return; } if (Application.isPlaying) { return; } _instance = this; if (defaultSkin == null) { defaultSkin = GUI.skin; } //if (Input.GetKey (KeyCode.KeypadEnter) || Input.GetKey ("enter")) //Deselect (); if (editorSkin == null) { editorSkin = (GUISkin)(AssetDatabase.LoadAssetAtPath("Assets/RPGKit/GUISkins/GUISkin.guiskin", typeof(GUISkin))); } GUI.skin = editorSkin; smallButtonSize = 35; if (window != null) { window.minSize = new Vector2(500, 500); window.maxSize = new Vector2(500, 500); } if (conversationList == null) { conversationList = AssetDatabase.LoadAssetAtPath("Assets/ConversationList.asset", typeof(ConversationList)) as ConversationList; } GUILayout.BeginHorizontal(); if (GUILayout.Button("Characters", GUILayout.Width(Screen.width * 0.5F), GUILayout.Height(50))) { assetType = AssetType.character; } if (GUILayout.Button("Main Story", GUILayout.Width(Screen.width * 0.5F), GUILayout.Height(50))) { assetType = AssetType.story; } GUILayout.EndHorizontal(); //conversationList = EditorGUILayout.ObjectField (conversationList, typeof(ConversationList), true) as ConversationList; if (assetType == AssetType.character) { _character = conversationList.characters [characterIndex]; } if (assetType == AssetType.story) { _character = conversationList.stories [0].chapters [0]; } //#here FindTarget(); EditorSceneManager.MarkAllScenesDirty(); if (targetObject == null) { eventTargetType = EventTargetTypes.global; } if (targetObject != null) { eventTargetType = EventTargetTypes.target; } if (targetObject != null) { Selection.activeObject = targetObject.transform; Selection.activeTransform = targetObject.transform; } scrollPos = EditorGUILayout.BeginScrollView(scrollPos, GUILayout.Width(Screen.width), GUILayout.Height(Screen.height * 0.9F)); if (assetType == AssetType.character) { DisplayCharacterCreation(); } if (assetType == AssetType.story) { if (GUILayout.Button("New Story")) { AddStory(); } for (int i = 0; i < conversationList.stories.Count; i++) { ConversationList.Stories curStory = conversationList.stories [i]; curStory.name = "Story"; if (GUILayout.Button(i.ToString() + ":" + curStory.name)) { curStory.isActive = !curStory.isActive; } //STORY IS ACTIVE if (curStory.isActive) { if (GUILayout.Button("Add Chapter")) { AddChapter(curStory); } int chapterIndex = 0; foreach (ConversationList.Chapters curChapter in curStory.chapters) { curChapter.name = "Chapter"; if (GUILayout.Button(chapterIndex.ToString() + ":" + curChapter.name)) { curChapter.isActive = !curChapter.isActive; } if (curChapter.isActive) { characterIndex = chapterIndex; foreach (ConversationList.Chapters otherChaps in curStory.chapters) { if (otherChaps != curChapter) { otherChaps.isActive = false; } } DisplayConversationContent(); GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); GUILayout.Space(40); GUILayout.BeginVertical(); GUILayout.Label("Notes: "); curChapter.notes = GUILayout.TextArea(curChapter.notes, GUILayout.Height(150)); GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.EndVertical(); //Make everything else disable } chapterIndex++; } } //Get current story } } EditorGUILayout.EndScrollView(); }
public static void Button(UnityEngine.Object target, MethodInfo methodInfo) { bool visible = ButtonUtility.IsVisible(target, methodInfo); if (!visible) { return; } if (methodInfo.GetParameters().All(p => p.IsOptional)) { ButtonAttribute buttonAttribute = (ButtonAttribute)methodInfo.GetCustomAttributes(typeof(ButtonAttribute), true)[0]; string buttonText = string.IsNullOrEmpty(buttonAttribute.Text) ? ObjectNames.NicifyVariableName(methodInfo.Name) : buttonAttribute.Text; bool buttonEnabled = ButtonUtility.IsEnabled(target, methodInfo); EButtonEnableMode mode = buttonAttribute.SelectedEnableMode; buttonEnabled &= mode == EButtonEnableMode.Always || mode == EButtonEnableMode.Editor && !Application.isPlaying || mode == EButtonEnableMode.Playmode && Application.isPlaying; bool methodIsCoroutine = methodInfo.ReturnType == typeof(IEnumerator); if (methodIsCoroutine) { buttonEnabled &= (Application.isPlaying ? true : false); } EditorGUI.BeginDisabledGroup(!buttonEnabled); if (GUILayout.Button(buttonText)) { object[] defaultParams = methodInfo.GetParameters().Select(p => p.DefaultValue).ToArray(); IEnumerator methodResult = methodInfo.Invoke(target, defaultParams) as IEnumerator; if (!Application.isPlaying) { // Set target object and scene dirty to serialize changes to disk EditorUtility.SetDirty(target); PrefabStage stage = PrefabStageUtility.GetCurrentPrefabStage(); if (stage != null) { // Prefab mode EditorSceneManager.MarkSceneDirty(stage.scene); } else { // Normal scene EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); } } else if (methodResult != null && target is MonoBehaviour behaviour) { behaviour.StartCoroutine(methodResult); } } EditorGUI.EndDisabledGroup(); } else { string warning = typeof(ButtonAttribute).Name + " works only on methods with no parameters"; HelpBox_Layout(warning, MessageType.Warning, context: target, logToConsole: true); } }
public static void Restart() { EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); EditorApplication.OpenProject(Environment.CurrentDirectory); }
/// <summary> /// Ensures that only approved component types are present in lighting scenes. /// </summary> private void EditorEnforceLightingSceneTypes(Scene scene) { if (EditorSceneManager.sceneCount == 1) { // There's nowhere to move invalid objects to. return; } List <Component> violations = new List <Component>(); if (EditorSceneUtils.EnforceSceneComponents(scene, Profile.PermittedLightingSceneComponentTypes, violations)) { Scene targetScene = default(Scene); for (int i = 0; i < EditorSceneManager.sceneCount; i++) { targetScene = EditorSceneManager.GetSceneAt(i); if (targetScene.path != scene.path) { // We'll move invalid items to this scene break; } } if (!targetScene.IsValid() || !targetScene.isLoaded) { // Something's gone wrong - don't proceed return; } HashSet <Transform> rootObjectsToMove = new HashSet <Transform>(); foreach (Component component in violations) { rootObjectsToMove.Add(component.transform.root); } List <string> rootObjectNames = new List <string>(); // Build a list of root objects so they know what's being moved foreach (Transform rootObject in rootObjectsToMove) { rootObjectNames.Add(rootObject.name); } EditorUtility.DisplayDialog( "Invalid components found in " + scene.name, "Only lighting-related components are permitted. The following GameObjects will be moved to another scene:\n\n" + String.Join("\n", rootObjectNames) + "\n\nTo disable this warning, un-check 'EditorEnforceLightingSceneTypes' in your SceneSystem profile.", "OK"); try { foreach (Transform rootObject in rootObjectsToMove) { EditorSceneManager.MoveGameObjectToScene(rootObject.gameObject, targetScene); } EditorGUIUtility.PingObject(rootObjectsToMove.FirstOrDefault()); } catch (Exception) { // This can happen if the move object operation fails. No big deal, we'll try again next time. return; } } }
// Mark ActiveSceneDirty private static void MarkActiveSceneDirty() { EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene()); }
void LoadNextScene() { EditorSceneManager.LoadScene(nextScene); }
private static Scene CurrentScene() { return(EditorSceneManager.GetActiveScene()); }
private void SetDirtyScene() { EditorUtility.SetDirty(_assetSpecialOffer); EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); }
private void OpenSceneAtPath() { // Executing this method in Unity 2017.1.1f1 results in console message // "Assertion failed: Assertion failed on expression: 'm_InstanceID != InstanceID_None'" EditorSceneManager.OpenScene(exampleScenePath, OpenSceneMode.Single); }
/// <summary> /// Collects the project dependencies from build scenes. /// </summary> public virtual void CollectProjectDependencies() { bool undoRecorded = false; // Remove NULL values from Dictionary. if (RemoveNullReferences() > 0) { Undo.RecordObject(this, "Update AssetReferenceResolver List"); undoRecorded = true; } List <UnityEngine.Object> allAssets = new List <UnityEngine.Object>(); Scene activeScene = EditorSceneManager.GetActiveScene(); for (int i = 0; i < EditorBuildSettings.scenes.Length; i++) { EditorBuildSettingsScene editorScene = EditorBuildSettings.scenes[i]; Scene scene; if (activeScene.path == editorScene.path) { scene = activeScene; } else { scene = EditorSceneManager.OpenScene(editorScene.path, OpenSceneMode.Additive); } UnityEngine.Object[] dependencies = EditorUtility.CollectDependencies(scene.GetRootGameObjects()); foreach (var sceneDependency in dependencies) { if (EditorUtility.IsPersistent(sceneDependency)) { allAssets.Add(sceneDependency); } } if (scene != activeScene) { EditorSceneManager.CloseScene(scene, true); } } foreach (var asset in allAssets) { if (asset == null || !CanBeSaved(asset)) { continue; } Type assetType = asset.GetType(); if (typeof(MonoScript).IsAssignableFrom(assetType) || typeof(UnityEditor.DefaultAsset).IsAssignableFrom(assetType)) { continue; } // If we're adding a new item to the type list, make sure we've recorded an undo for the object. if (string.IsNullOrEmpty(ResolveGuid(asset))) { if (!undoRecorded) { Undo.RecordObject(this, "Update AssetReferenceResolver List"); undoRecorded = true; } string guid = Guid.NewGuid().ToString("N"); Add(guid, asset); } } MaterialPropertiesResolver.Current.CollectMaterials(); }
void GenerateData(string path) { var parent = Directory.GetParent(path).FullName; parent = parent.Substring(Application.dataPath.Length - "Assets".Length); // full path -> unity path var fileName = Path.GetFileName(path); var rootFolderPath = AssetDatabase.GUIDToAssetPath( AssetDatabase.CreateFolder(parent, fileName) ); var materialFolderPath = AssetDatabase.GUIDToAssetPath( AssetDatabase.CreateFolder(rootFolderPath, "Materials") ); var shaderFolderPath = AssetDatabase.GUIDToAssetPath( AssetDatabase.CreateFolder(rootFolderPath, "Shaders") ); // shader var templateShaderPath = AssetDatabase.GetAssetPath(m_GeneratorSettings.TemplateShader); var templateShaderExt = Path.GetExtension(templateShaderPath); var newShaderPath = Path.Combine(shaderFolderPath, fileName) + templateShaderExt; AssetDatabase.CopyAsset(templateShaderPath, newShaderPath); var newShader = AssetDatabase.LoadAssetAtPath(newShaderPath, typeof(Shader)) as Shader; // material var newMaterialPath = Path.Combine(materialFolderPath, fileName) + ".mat"; var newMaterial = new Material(newShader); AssetDatabase.CreateAsset(newMaterial, newMaterialPath); // scene var templateScenePath = AssetDatabase.GetAssetPath(m_GeneratorSettings.TemplateScene); var newScenePath = Path.Combine(rootFolderPath, fileName) + ".unity"; AssetDatabase.CopyAsset(templateScenePath, newScenePath); var newScene = EditorSceneManager.OpenScene(newScenePath, OpenSceneMode.Additive); // bind Material to MeshRenderer var meshRenderer = newScene.GetRootGameObjects() .Select(go => go.GetComponent <MeshRenderer>()) .FirstOrDefault(mr => mr != null); if (meshRenderer != null) { meshRenderer.material = newMaterial; } // bind Material to SoundShader var soundShader = newScene.GetRootGameObjects() .Select(go => go.GetComponent <SoundShader>()) .FirstOrDefault(ss => ss != null); if (soundShader != null) { soundShader.SetMaterial(newMaterial); } // save EditorSceneManager.SaveScene(newScene); EditorSceneManager.CloseScene(newScene, true); // refresh AssetDatabase.Refresh(); EditorGUIUtility.PingObject(newShader); // open scene if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { EditorSceneManager.OpenScene(newScenePath); } }
internal void SwitchToAssetMode(bool selectAvatarAsset) { foreach (var state in m_SceneStates) { if (state.view == null) { continue; } state.view.sceneViewState.showFog = state.state.showFog; state.view.sceneViewState.showFlares = state.state.showFlares; state.view.sceneViewState.showMaterialUpdate = state.state.showMaterialUpdate; state.view.sceneViewState.showSkybox = state.state.showSkybox; state.view.sceneViewState.showImageEffects = state.state.showImageEffects; state.view.sceneViewState.showParticleSystems = state.state.showParticleSystems; } m_EditMode = EditMode.Stopping; DestroyEditor(); ChangeInspectorLock(m_InspectorLocked); // if the user started play mode While in Edit mode it not clear what we should do // for now let the active scene open and do nothing if (!EditorApplication.isPlaying) { EditorApplication.CallbackFunction CleanUpSceneOnDestroy = null; CleanUpSceneOnDestroy = () => { string currentScene = SceneManager.GetActiveScene().path; if (currentScene.Length > 0) { // in this case the user did save manually the current scene and want to keep it or // he did open a new scene // do nothing } // Restore scene that was loaded when user pressed Configure button else if (sceneSetup != null && sceneSetup.Length > 0) { EditorSceneManager.RestoreSceneManagerSetup(sceneSetup); sceneSetup = null; } else { EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects); } // Make sure that we restore the "original" selection if we exit Avatar Editing mode // from the avatar tooling itself (e.g by clicking done). if (selectAvatarAsset) { SelectAsset(); } if (!m_CameFromImportSettings) { m_EditMode = EditMode.NotEditing; } EditorApplication.update -= CleanUpSceneOnDestroy; }; EditorApplication.update += CleanUpSceneOnDestroy; } // Reset back the Edit Mode specific states (they probably should be better encapsulated) m_GameObject = null; m_ModelBones = null; }
internal void SwitchToEditMode() { // Ensure we show the main stage before starting editing the Avatar since it will be edited on the Main stage (we are using a main scene for it) if (StageNavigationManager.instance.currentStage is PrefabStage) { StageNavigationManager.instance.GoToMainStage(StageNavigationManager.Analytics.ChangeType.GoToMainViaAvatarSetup); } m_EditMode = EditMode.Starting; // Lock inspector ChangeInspectorLock(true); // Store current setup in hierarchy sceneSetup = EditorSceneManager.GetSceneManagerSetup(); // Load temp scene Scene scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects); scene.name = "Avatar Configuration"; // Instantiate character m_GameObject = Instantiate(prefab) as GameObject; if (serializedAssetImporter.FindProperty("m_OptimizeGameObjects").boolValue) { AnimatorUtility.DeoptimizeTransformHierarchy(m_GameObject); } SerializedProperty humanBoneArray = serializedAssetImporter.FindProperty("m_HumanDescription.m_Human"); // First get all available modelBones Dictionary <Transform, bool> modelBones = AvatarSetupTool.GetModelBones(m_GameObject.transform, true, null); AvatarSetupTool.BoneWrapper[] humanBones = AvatarSetupTool.GetHumanBones(humanBoneArray, modelBones); m_ModelBones = AvatarSetupTool.GetModelBones(m_GameObject.transform, false, humanBones); Selection.activeObject = m_GameObject; // Unfold all nodes in hierarchy // TODO@MECANIM: Only expand actual bones foreach (SceneHierarchyWindow shw in Resources.FindObjectsOfTypeAll(typeof(SceneHierarchyWindow))) { shw.SetExpandedRecursive(m_GameObject.GetInstanceID(), true); } CreateEditor(); m_EditMode = EditMode.Editing; // Frame in scene view m_SceneStates = new List <SceneStateCache>(); foreach (SceneView s in SceneView.sceneViews) { m_SceneStates.Add(new SceneStateCache { state = new SceneView.SceneViewState(s.sceneViewState), view = s }); s.sceneViewState.showFlares = false; s.sceneViewState.showMaterialUpdate = false; s.sceneViewState.showFog = false; s.sceneViewState.showSkybox = false; s.sceneViewState.showImageEffects = false; s.sceneViewState.showParticleSystems = false; s.FrameSelected(); } }
private static void MakeScene(string path, string name) { var newScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects); EditorSceneManager.SaveScene(newScene, "Assets/" + path + "/" + name + ".unity"); }
public override void OnInspectorGUI() { serializedObject.UpdateIfRequiredOrScript(); GUI.enabled = cloth.Initialized; EditorGUI.BeginChangeCheck(); editMode = GUILayout.Toggle(editMode, new GUIContent("Edit particles", Resources.Load <Texture2D>("EditParticles")), "LargeButton"); if (EditorGUI.EndChangeCheck()) { SceneView.RepaintAll(); } GUI.enabled = true; EditorGUILayout.LabelField("Status: " + (cloth.Initialized ? "Initialized":"Not initialized")); GUI.enabled = (cloth.SharedTopology != null); if (GUILayout.Button("Initialize")) { if (!cloth.Initialized) { EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); CoroutineJob job = new CoroutineJob(); routine = job.Start(cloth.GeneratePhysicRepresentationForMesh()); EditorCoroutine.ShowCoroutineProgressBar("Generating physical representation...", ref routine); EditorGUIUtility.ExitGUI(); } else { if (EditorUtility.DisplayDialog("Actor initialization", "Are you sure you want to re-initialize this actor?", "Ok", "Cancel")) { EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); CoroutineJob job = new CoroutineJob(); routine = job.Start(cloth.GeneratePhysicRepresentationForMesh()); EditorCoroutine.ShowCoroutineProgressBar("Generating physical representation...", ref routine); EditorGUIUtility.ExitGUI(); } } } GUI.enabled = true; if (cloth.SharedTopology == null) { EditorGUILayout.HelpBox("No ObiMeshTopology asset present.", MessageType.Info); } GUI.enabled = cloth.Initialized; if (GUILayout.Button("Set Rest State")) { Undo.RecordObject(cloth, "Set rest state"); cloth.PullDataFromSolver(ParticleData.POSITIONS | ParticleData.VELOCITIES); } GUI.enabled = true; Editor.DrawPropertiesExcluding(serializedObject, "m_Script"); // Apply changes to the serializedProperty if (GUI.changed) { serializedObject.ApplyModifiedProperties(); } }
private void OpenSceneAtPathAdditive() { EditorSceneManager.OpenScene(exampleScenePath, OpenSceneMode.Additive); }
private void Save() { EditorUtility.SetDirty((Component)thisDevice); EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene()); }
/// <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(); }
public override void OnInspectorGUI() { DrawToolbarGUI(); serializedObject.Update(); bool dirty = DrawGeneralGUI(); EditorGUILayout.BeginVertical(GUI.skin.box); showMarkers = Foldout(showMarkers, string.Format("2D Markers (Count: {0})", pMarkers.arraySize)); if (showMarkers) { DrawMarkersGUI(ref dirty); } EditorGUILayout.EndVertical(); if (pTarget.enumValueIndex == (int)OnlineMapsTarget.texture) { EditorGUILayout.BeginVertical(GUI.skin.box); showCreateTexture = Foldout(showCreateTexture, "Create texture"); if (showCreateTexture) { DrawCreateTextureGUI(ref dirty); } EditorGUILayout.EndVertical(); } EditorGUILayout.BeginVertical(GUI.skin.box); showAdvanced = Foldout(showAdvanced, "Advanced"); if (showAdvanced) { DrawAdvancedGUI(); } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); showTroubleshooting = Foldout(showTroubleshooting, "Troubleshooting"); if (showTroubleshooting) { DrawTroubleshootingGUI(ref dirty); } EditorGUILayout.EndVertical(); CheckNullControl(); #if UNITY_WEBPLAYER CheckJSLoader(); #endif serializedObject.ApplyModifiedProperties(); if (dirty) { EditorUtility.SetDirty(api); if (!Application.isPlaying) { #if UNITY_5_3P EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene()); #endif } else { api.Redraw(); } } }
/// <summary> /// Splits the scene into tiles. /// </summary> void SplitScene(SceneCollection layer) { warning = ""; splits [layer.layerNumber] = new Dictionary <string, GameObject> (); GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType <GameObject> (); FindSceneGO(layer.prefixScene, allObjects, splits [layer.layerNumber]); ClearSceneGO(layer); foreach (var item in allObjects) { if (item == null || item.transform.parent != null || !item.name.StartsWith(layer.prefixName) || item.GetComponent <SceneSplitManager> () != null || item.GetComponent <SceneCollection> () != null || item.GetComponent <SceneSplitterSettings> () != null) { continue; } string splitName = layer.prefixScene + GetID(item.transform.position, layer); UnityEngine.SceneManagement.Scene scene = EditorSceneManager.GetSceneByName(splitName); //EditorSceneManager.NewScene (NewSceneSetup.EmptyScene, NewSceneMode.Additive); if (scene.name == null) { string splitSceneName = splitName + ".unity"; string sceneName = layer.path + splitSceneName; bool contains = false; foreach (var nameSplit in layer.names) { if (nameSplit == splitSceneName) { contains = true; break; } } if (!contains) { List <string> names = new List <string> (); names.AddRange(layer.names); names.Add(splitSceneName); layer.names = names.ToArray(); scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); EditorSceneManager.SaveScene(scene, sceneName); loadedScenes.Add(scene); } else { scene = EditorSceneManager.OpenScene(sceneName, OpenSceneMode.Additive); loadedScenes.Add(scene); } } } allObjects = UnityEngine.Object.FindObjectsOfType <GameObject> (); FindSceneGO(layer.prefixScene, allObjects, splits [layer.layerNumber]); ClearSceneGO(layer); foreach (var item in allObjects) { if (item == null || item.transform.parent != null || !item.name.StartsWith(layer.prefixName) || item.GetComponent <SceneSplitManager> () != null || item.GetComponent <SceneCollection> () != null || item.GetComponent <SceneSplitterSettings> () != null) { continue; } string itemId = GetID(item.transform.position, layer); GameObject split = null; if (!splits [layer.layerNumber].TryGetValue(itemId, out split)) { split = new GameObject(layer.prefixScene + itemId); SceneSplitManager sceneSplitManager = split.AddComponent <SceneSplitManager> (); sceneSplitManager.sceneName = split.name; sceneSplitManager.size = new Vector3(layer.xSize != 0 ? layer.xSize : 100, layer.ySize != 0 ? layer.ySize : 100, layer.zSize != 0 ? layer.zSize : 100); sceneSplitManager.position = GetSplitPosition(item.transform.position, layer); sceneSplitManager.color = layer.color; splits [layer.layerNumber].Add(itemId, split); Vector3 splitPosId = GetSplitPositionID(item.transform.position, layer); if (layer.xSplitIs) { if (splitPosId.x < layer.xLimitsx) { layer.xLimitsx = (int)splitPosId.x; } if (splitPosId.x > layer.xLimitsy) { layer.xLimitsy = (int)splitPosId.x; } } else { layer.xLimitsx = 0; layer.xLimitsy = 0; } if (layer.ySplitIs) { if (splitPosId.y < layer.yLimitsx) { layer.yLimitsx = (int)splitPosId.y; } if (splitPosId.y > layer.yLimitsy) { layer.yLimitsy = (int)splitPosId.y; } } else { layer.yLimitsx = 0; layer.yLimitsy = 0; } if (layer.zSplitIs) { if (splitPosId.z < layer.zLimitsx) { layer.zLimitsx = (int)splitPosId.x; } if (splitPosId.z > layer.zLimitsy) { layer.zLimitsy = (int)splitPosId.z; } } else { layer.zLimitsx = 0; layer.zLimitsy = 0; } UnityEngine.SceneManagement.Scene scene = EditorSceneManager.GetSceneByName(sceneSplitManager.sceneName); EditorSceneManager.MoveGameObjectToScene(split, scene); } item.transform.SetParent(split.transform); } if (splits.Count == 0) { warning = "No objects to split. Check GameObject or Scene Prefix."; } foreach (var item in loadedScenes) { if (!string.IsNullOrEmpty(item.name) && GameObject.Find(item.name) == null) { GameObject split = new GameObject(item.name); SceneSplitManager sceneSplitManager = split.AddComponent <SceneSplitManager> (); sceneSplitManager.sceneName = split.name; sceneSplitManager.size = new Vector3(layer.xSize != 0 ? layer.xSize : 100, layer.ySize != 0 ? layer.ySize : 100, layer.zSize != 0 ? layer.zSize : 100); int posx; int posy; int posz; Streamer.SceneNameToPos(layer, item.name, out posx, out posy, out posz); posx *= layer.xSize; posy *= layer.ySize; posz *= layer.zSize; sceneSplitManager.position = GetSplitPosition(new Vector3(posx, posy, posz), layer); sceneSplitManager.color = layer.color; splits [layer.layerNumber].Add(split.name.Replace(layer.prefixScene, ""), split); EditorSceneManager.MoveGameObjectToScene(split, item); } } }
/// <summary> /// If a manager scene is being used, this loads the scene in editor and ensures that an instance of the MRTK has been added to it. /// </summary> private void EditorUpdateManagerScene() { if (!Profile.UseManagerScene || !Profile.EditorManageLoadedScenes) { // Nothing to do here. return; } if (EditorSceneUtils.LoadScene(Profile.ManagerScene, true, out Scene scene)) { // If we're managing scene hierarchy, move this to the front if (Profile.EditorEnforceSceneOrder) { Scene currentFirstScene = EditorSceneManager.GetSceneAt(0); if (currentFirstScene.name != scene.name) { EditorSceneManager.MoveSceneBefore(scene, currentFirstScene); } } if (Time.realtimeSinceStartup > managerSceneInstanceCheckTime) { managerSceneInstanceCheckTime = Time.realtimeSinceStartup + managerSceneInstanceCheckInterval; // Check for an MRTK instance bool foundToolkitInstance = false; try { foreach (GameObject rootGameObject in scene.GetRootGameObjects()) { MixedRealityToolkit instance = rootGameObject.GetComponent <MixedRealityToolkit>(); if (instance != null) { foundToolkitInstance = true; // If we found an instance, and it's not the active instance, we probably want to activate it if (instance != MixedRealityToolkit.Instance) { // The only exception would be if the new instance has a different profile than the current instance // If that's the case, we could end up ping-ponging between two sets of manager scenes if (!instance.HasActiveProfile) { // If it doesn't have a profile, set it to our current profile instance.ActiveProfile = MixedRealityToolkit.Instance.ActiveProfile; } else if (instance.ActiveProfile != MixedRealityToolkit.Instance.ActiveProfile) { Debug.LogWarning("The active profile of the instance in your manager scene is different from the profile that loaded your scene. This is not recommended."); } else { Debug.LogWarning("Setting the manager scene MixedRealityToolkit instance to the active instance."); MixedRealityToolkit.SetActiveInstance(instance); } } break; } } } catch (Exception) { // This can happen if the scene isn't valid // Not an issue - we'll take care of it on the next update. return; } if (!foundToolkitInstance) { GameObject mrtkGo = new GameObject("MixedRealityToolkit"); MixedRealityToolkit toolkitInstance = mrtkGo.AddComponent <MixedRealityToolkit>(); try { SceneManager.MoveGameObjectToScene(mrtkGo, scene); // Set the scene as dirty EditorSceneManager.MarkSceneDirty(scene); } catch (Exception) { // This can happen if the scene isn't valid // Not an issue - we'll take care of it on the next update. // Destroy the new manager GameObject.DestroyImmediate(mrtkGo); return; } MixedRealityToolkit.SetActiveInstance(toolkitInstance); Debug.LogWarning("Didn't find a MixedRealityToolkit instance in your manager scene. Creating one now."); } } } else { Debug.Log("Couldn't load manager scene!"); } }
public override void OnInspectorGUI() { // Capture Cameras GUILayout.Label("Capture Cameras", EditorStyles.boldLabel); EditorGUILayout.PropertyField(regularCamera, new GUIContent("Regular Camera"), true); EditorGUILayout.PropertyField(stereoCamera, new GUIContent("Stereo Camera"), true); // Capture Options Section GUILayout.Label("Capture Options", EditorStyles.boldLabel); screenshot.saveFolder = EditorGUILayout.TextField("Save Folder", screenshot.saveFolder); screenshot.captureMode = (CaptureMode)EditorGUILayout.EnumPopup("Capture Mode", screenshot.captureMode); if (screenshot.captureMode == CaptureMode._360) { screenshot.projectionType = (ProjectionType)EditorGUILayout.EnumPopup("Projection Type", screenshot.projectionType); } if (screenshot.captureMode == CaptureMode._360 && screenshot.projectionType == ProjectionType.CUBEMAP) { screenshot.stereoMode = StereoMode.NONE; } else { screenshot.stereoMode = (StereoMode)EditorGUILayout.EnumPopup("Stereo Mode", screenshot.stereoMode); } if (screenshot.stereoMode != StereoMode.NONE) { screenshot.interpupillaryDistance = EditorGUILayout.FloatField("Interpupillary Distance", screenshot.interpupillaryDistance); } // Capture Options Section GUILayout.Label("Screenshot Settings", EditorStyles.boldLabel); screenshot.resolutionPreset = (ResolutionPreset)EditorGUILayout.EnumPopup("Resolution Preset", screenshot.resolutionPreset); if (screenshot.resolutionPreset == ResolutionPreset.CUSTOM) { screenshot.frameWidth = EditorGUILayout.IntField("Frame Width", screenshot.frameWidth); screenshot.frameHeight = EditorGUILayout.IntField("Frame Height", screenshot.frameHeight); } if (screenshot.captureMode == CaptureMode._360) { screenshot.cubemapFaceSize = (CubemapFaceSize)EditorGUILayout.EnumPopup("Cubemap Face Size", screenshot.cubemapFaceSize); } screenshot.antiAliasingSetting = (AntiAliasingSetting)EditorGUILayout.EnumPopup("Anti Aliasing Settings", screenshot.antiAliasingSetting); #if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN // Capture Options Section GUILayout.Label("Encoder Settings", EditorStyles.boldLabel); if (!FreeTrial.Check()) { screenshot.gpuEncoding = EditorGUILayout.Toggle("GPU Encoding", screenshot.gpuEncoding); } #endif //// Tools Section //GUILayout.Label("Tools", EditorStyles.boldLabel); GUILayout.Space(10); if (GUILayout.Button("Browse")) { // Open video save directory Utils.BrowseFolder(screenshot.saveFolder); } if (GUI.changed) { EditorUtility.SetDirty(target); EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); } // Apply changes to the serializedProperty - always do this at the end of OnInspectorGUI. serializedObject.ApplyModifiedProperties(); }
private void SectionReviewNames() { EditorGUILayout.LabelField("Review Failed Names", EditorStyles.boldLabel); GUILayout.BeginHorizontal(); bool btnPrevious = GUILayout.Button("Previous"); bool btnNext = GUILayout.Button("Next"); GUILayout.EndHorizontal(); if (btnPrevious) { reviewedObjectIndex--; } if (btnNext) { reviewedObjectIndex++; } if (btnPrevious || btnNext) { reviewedObjectIndex = Mathf.Clamp(reviewedObjectIndex, 0, badObjects.Count - 1); Selection.activeGameObject = badObjects[reviewedObjectIndex].gameObject; SceneView.FrameLastActiveSceneView(); enteredName = string.Empty; randomIdentifier = GenerateRandomIdentifier(); } if (reviewedObjectIndex > -1) { var reviewedObject = badObjects[reviewedObjectIndex]; EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Current name:"); GUI.enabled = false; GUILayout.TextField(reviewedObject.name); GUI.enabled = true; GUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Object's location:"); enteredName = EditorGUILayout.TextField(enteredName); EditorGUILayout.EndHorizontal(); EditorGUILayout.HelpBox("Expecting a room name, e.g. 'Engineering Lobby' or 'Central Primary Hallway'.", MessageType.Info); if (string.IsNullOrWhiteSpace(enteredName) == false) { string devicePrefix = regexes[activeWindowTab].Split(' ')[0].Substring(1); string proposedName = $"{devicePrefix} - {enteredName} - {randomIdentifier}"; EditorGUILayout.BeginHorizontal(); GUI.enabled = false; EditorGUILayout.TextField(proposedName); GUI.enabled = true; if (Regex.Match(proposedName, regexes[activeWindowTab]).Success) { GUILayout.Label("Proposed name is valid"); reviewedObject.name = proposedName; modifiedObjects.Add(reviewedObject); } else { GUILayout.Label("Proposed name is invalid"); } EditorGUILayout.EndHorizontal(); } EditorGUILayout.Space(10); if (modifiedObjects.Count > 0 && EditorUIUtils.BigAssButton("Save All")) { foreach (var gameObject in modifiedObjects) { EditorUtility.SetDirty(gameObject); } EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene()); reviewedObjectIndex = -1; modifiedObjects.Clear(); PopulateList(); ScanList(); } } }
private void Outline(MaterialEditor materialEditor, MaterialProperty[] properties, GUIStyle style, bool toggle) { bool ini = toggle; toggle = EditorGUILayout.BeginToggleGroup("3.Outline", toggle); if (ini != toggle && !Application.isPlaying) { EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); } if (toggle) { targetMat.EnableKeyword("OUTBASE_ON"); EditorGUILayout.BeginVertical(style); { materialEditor.ShaderProperty(properties[14], properties[14].displayName); materialEditor.ShaderProperty(properties[15], properties[15].displayName); materialEditor.ShaderProperty(properties[16], properties[16].displayName); materialEditor.ShaderProperty(properties[17], properties[17].displayName); MaterialProperty outline8dir = ShaderGUI.FindProperty("_Outline8Directions", properties); if (outline8dir.floatValue == 1) { targetMat.EnableKeyword("OUTBASE8DIR_ON"); } else { targetMat.DisableKeyword("OUTBASE8DIR_ON"); } materialEditor.ShaderProperty(properties[19], properties[19].displayName); MaterialProperty outlinePixel = ShaderGUI.FindProperty("_OutlineIsPixel", properties); if (outlinePixel.floatValue == 1) { targetMat.EnableKeyword("OUTBASEPIXELPERF_ON"); materialEditor.ShaderProperty(properties[20], properties[20].displayName); } else { targetMat.DisableKeyword("OUTBASEPIXELPERF_ON"); materialEditor.ShaderProperty(properties[18], properties[18].displayName); } materialEditor.ShaderProperty(properties[21], properties[21].displayName); MaterialProperty outlineTex = ShaderGUI.FindProperty("_OutlineTexToggle", properties); if (outlineTex.floatValue == 1) { targetMat.EnableKeyword("OUTTEX_ON"); materialEditor.ShaderProperty(properties[22], properties[22].displayName); materialEditor.ShaderProperty(properties[23], properties[23].displayName); materialEditor.ShaderProperty(properties[24], properties[24].displayName); materialEditor.ShaderProperty(properties[25], properties[25].displayName); MaterialProperty outlineTexGrey = ShaderGUI.FindProperty("_OutlineTexGrey", properties); if (outlineTexGrey.floatValue == 1) { targetMat.EnableKeyword("OUTGREYTEXTURE_ON"); } else { targetMat.DisableKeyword("OUTGREYTEXTURE_ON"); } } else { targetMat.DisableKeyword("OUTTEX_ON"); } materialEditor.ShaderProperty(properties[26], properties[26].displayName); MaterialProperty outlineDistort = ShaderGUI.FindProperty("_OutlineDistortToggle", properties); if (outlineDistort.floatValue == 1) { targetMat.EnableKeyword("OUTDIST_ON"); materialEditor.ShaderProperty(properties[27], properties[27].displayName); materialEditor.ShaderProperty(properties[28], properties[28].displayName); materialEditor.ShaderProperty(properties[29], properties[29].displayName); materialEditor.ShaderProperty(properties[30], properties[30].displayName); } else { targetMat.DisableKeyword("OUTDIST_ON"); } EditorGUILayout.Separator(); materialEditor.ShaderProperty(properties[71], properties[71].displayName); MaterialProperty onlyOutline = ShaderGUI.FindProperty("_OnlyOutline", properties); if (onlyOutline.floatValue == 1) { targetMat.EnableKeyword("ONLYOUTLINE_ON"); } else { targetMat.DisableKeyword("ONLYOUTLINE_ON"); } } EditorGUILayout.EndVertical(); } else { targetMat.DisableKeyword("OUTBASE_ON"); } EditorGUILayout.EndToggleGroup(); }
/// <summary> /// Tell Unity that a change has been made to a specified object and we have to save the scene. /// </summary> public static void MarkSceneDirty(GameObject gameObject) { // TODO: Undo.RecordObject also marks the scene dirty, so this will no longer be necessary once undo support is added. EditorSceneManager.MarkSceneDirty(gameObject.scene); }
public void CheckMissingComponentsOnScenes() { var buildScenes = EditorBuildSettings.scenes; var missingComponentsReport = new List <(string, string)>(); var missingFieldsReport = new List <(string, string, string, string)>(); foreach (var scene in buildScenes) { var currentScene = EditorSceneManager.OpenScene(scene.path, OpenSceneMode.Single); var currentSceneName = currentScene.name; var allGO = GameObject.FindObjectsOfType <GameObject>(); foreach (var go in allGO) { Component[] components = go.GetComponents <Component>(); foreach (Component c in components) { var parent = go.transform.parent; var parentName = parent ? parent.name + '/' : ""; if (c == null) { missingComponentsReport.Add((currentSceneName, parentName + go.name)); } else { var so = new SerializedObject(c); var missingRefs = GetMissingRefs(so); foreach (var miss in missingRefs) { missingFieldsReport.Add((currentSceneName, parentName + go.name, c.name, miss)); } } } } } // Form report about missing components var report = new StringBuilder(); foreach (var s in missingComponentsReport) { var missingComponentMsg = $"Missing component found in scene {s.Item1}, GameObject {s.Item2}"; Logger.Log(missingComponentMsg, Category.Tests); report.AppendLine(missingComponentMsg); } Assert.IsEmpty(missingComponentsReport, report.ToString()); // Form report about missing refs report = new StringBuilder(); foreach (var s in missingFieldsReport) { var missingFieldsMsg = $"Missing reference found in scene {s.Item1}, GameObject {s.Item2}, Component {s.Item3}, FieldName {s.Item4}"; Logger.Log(missingFieldsMsg, Category.Tests); report.AppendLine(missingFieldsMsg); } Assert.IsEmpty(missingFieldsReport, report.ToString()); }
/// <summary>UI</summary> private void OnGUI() { bool listHasChanged = false; scrollPos = EditorGUILayout.BeginScrollView(scrollPos); EditorGUILayout.BeginHorizontal(); GUILayout.Space(10); EditorGUILayout.BeginVertical(); GUILayout.Space(20); EditorGUILayout.LabelField("Materials to look for:", EditorStyles.boldLabel); // Pick from selection if (GUILayout.Button("Pick from current selection")) { matsToLookFor.Clear(); for (int i = 0; i < Selection.gameObjects.Length; ++i) { Renderer ren = Selection.gameObjects[i].GetComponent <Renderer>(); if (ren != null) { for (int j = 0; j < ren.sharedMaterials.Length; ++j) { if (!matsToLookFor.Contains(ren.sharedMaterials[j])) { matsToLookFor.Add(ren.sharedMaterials[j]); } } } } listHasChanged = true; } GUILayout.Space(10); // Show list of selected materials for (int i = 0; i < matsToLookFor.Count; ++i) { Material newMat = (Material)EditorGUILayout.ObjectField(matsToLookFor[i], typeof(Material), true); if (newMat != matsToLookFor[i]) { matsToLookFor[i] = newMat; listHasChanged = true; } // remove empty values if (newMat == null) { matsToLookFor.RemoveAt(i); } } // Add an empty one at the end Material additionalMat = (Material)EditorGUILayout.ObjectField(null, typeof(Material), true); // And add this one to our list, if the user does not want it to be emtpy anymore if (additionalMat != null) { if (!matsToLookFor.Contains(additionalMat)) { matsToLookFor.Add(additionalMat); } listHasChanged = true; } // Update list of renderers, if necessary if (listHasChanged) { PickAllRenderers(); } GUILayout.Space(20); // Show list of renderers EditorGUILayout.LabelField("Renderers for these materials in scene:", EditorStyles.boldLabel); if (objWithMats.Count > 0) { // Show list of connected renderers for (int i = 0; i < objWithMats.Count; ++i) { EditorGUILayout.ObjectField(objWithMats[i], typeof(Renderer), true); } GUILayout.Space(10); // Select button if (GUILayout.Button("Select these objects")) { // Generate list Object[] selGOs = new GameObject[objWithMats.Count]; for (int i = 0; i < objWithMats.Count; ++i) { selGOs[i] = objWithMats[i].gameObject; } Selection.objects = selGOs; } GUILayout.Space(30); // Material replacement EditorGUILayout.LabelField("Material replacement:", EditorStyles.boldLabel); EditorGUILayout.LabelField("Replace above materials with:"); replaceMat = (Material)EditorGUILayout.ObjectField(replaceMat, typeof(Material), true); GUILayout.Space(5); // Replace button if (GUILayout.Button("Replace in current scene!")) { int countMats = 0; int countObjs = 0; // Run replacement for (int i = 0; i < objWithMats.Count; ++i) { bool anyReplacment = false; Material[] matsHere = objWithMats[i].sharedMaterials; for (int j = 0; j < matsHere.Length; ++j) { if (matsToLookFor.Contains(objWithMats[i].sharedMaterials[j])) { matsHere[j] = replaceMat; ++countMats; anyReplacment = true; } } if (anyReplacment) { objWithMats[i].sharedMaterials = matsHere; ++countObjs; } } // Inform Debug.LogFormat("Replaced {0} materials in {1} objects", countMats, countObjs); // Update PickAllRenderers(); // Set dirty EditorSceneManager.MarkSceneDirty(UnityEngine.SceneManagement.SceneManager.GetActiveScene()); } } else { EditorGUILayout.LabelField("This applys to none of the objects in the current scene"); GUILayout.Space(30); EditorGUILayout.LabelField("Replacement is not possible here"); } EditorGUILayout.EndVertical(); GUILayout.Space(10); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndScrollView(); }
private static void SteamVROpenScene() { EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); EditorSceneManager.OpenScene("Assets/SteamVR/InteractionSystem/Samples/Interactions_Example.unity"); }
public override void OnInspectorGUI() { var defaulGUIColor = GUI.color; EditorGUI.BeginChangeCheck(); GUILayout.Label("Name:", EditorStyles.boldLabel); _script.Name = EditorGUILayout.TextField(_script.Name); //GUILayout.EndHorizontal(); GUILayout.Label("Description", EditorStyles.boldLabel); EditorStyles.textField.wordWrap = true; _script.Description = EditorGUILayout.TextArea(_script.Description, GUILayout.MinHeight(100), GUILayout.MaxHeight(200), GUILayout.MaxWidth(450)); //GUILayout.BeginHorizontal(); GUILayout.Label("Nation:", EditorStyles.boldLabel); _script.countryIndex = EditorGUILayout.Popup(_script.countryIndex, _script.GetCountries()); //GUILayout.EndHorizontal(); //GUILayout.BeginHorizontal(); GUILayout.Label("Surfaces:", EditorStyles.boldLabel); //t.Surfaces = EditorGUILayout.TextField(t.Surfaces); GUILayout.BeginHorizontal(); { GUI.color = _script.Tarmac ? Color.yellow : defaulGUIColor; if (GUILayout.Button("Tarmac")) { _script.Tarmac = !_script.Tarmac; } GUI.color = _script.Gravel ? Color.yellow : defaulGUIColor; if (GUILayout.Button("Gravel")) { _script.Gravel = !_script.Gravel; } GUI.color = _script.Dirt ? Color.yellow : defaulGUIColor; if (GUILayout.Button("Dirt")) { _script.Dirt = !_script.Dirt; } GUI.color = _script.Ice ? Color.yellow : defaulGUIColor; if (GUILayout.Button("Ice")) { _script.Ice = !_script.Ice; } GUI.color = _script.Snow ? Color.yellow : defaulGUIColor; if (GUILayout.Button("Snow")) { _script.Snow = !_script.Snow; } GUI.color = defaulGUIColor; } GUILayout.EndHorizontal(); //GUILayout.EndHorizontal(); //GUILayout.BeginHorizontal(); GUILayout.Label("Tags:", EditorStyles.boldLabel); _script.Tags = EditorGUILayout.TextField(_script.Tags); //GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); //GUILayout.Label("Save Times:", EditorStyles.boldLabel); _script.SaveTimes = EditorGUILayout.Toggle("Save Times:", _script.SaveTimes); _script.multiLaps = EditorGUILayout.Toggle("Multiple laps:", _script.multiLaps); GUILayout.EndHorizontal(); if (EditorGUI.EndChangeCheck()) { #if !(UNITY_5_0 || UNITY_5_1 || UNITY_5_2) EditorSceneManager.MarkSceneDirty(_script.gameObject.scene); EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene()); #endif EditorUtility.SetDirty(_script); } //serializedObject.ApplyModifiedProperties(); }
public bool ScanScenes(string[] scenePaths, bool includeSceneDependencies, bool showProgressBar) { if (scenePaths.Length == 0) { return(true); } bool formerForceEditorModeSerialization = UnitySerializationUtility.ForceEditorModeSerialization; try { UnitySerializationUtility.ForceEditorModeSerialization = true; bool hasDirtyScenes = false; for (int i = 0; i < EditorSceneManager.sceneCount; i++) { if (EditorSceneManager.GetSceneAt(i).isDirty) { hasDirtyScenes = true; break; } } if (hasDirtyScenes && !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { return(false); } var oldSceneSetup = EditorSceneManager.GetSceneManagerSetup(); try { for (int i = 0; i < scenePaths.Length; i++) { var scenePath = scenePaths[i]; if (showProgressBar && EditorUtility.DisplayCancelableProgressBar("Scanning scenes for AOT support", "Scene " + (i + 1) + "/" + scenePaths.Length + " - " + scenePath, (float)i / scenePaths.Length)) { return(false); } EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single); var sceneGOs = UnityEngine.Object.FindObjectsOfType <GameObject>(); foreach (var go in sceneGOs) { if ((go.hideFlags & HideFlags.DontSaveInBuild) == 0) { foreach (var component in go.GetComponents <ISerializationCallbackReceiver>()) { try { this.allowRegisteringScannedTypes = true; component.OnBeforeSerialize(); var prefabSupporter = component as ISupportsPrefabSerialization; if (prefabSupporter != null) { // Also force a serialization of the object's prefab modifications, in case there are unknown types in there List <UnityEngine.Object> objs = null; var mods = UnitySerializationUtility.DeserializePrefabModifications(prefabSupporter.SerializationData.PrefabModifications, prefabSupporter.SerializationData.PrefabModificationsReferencedUnityObjects); UnitySerializationUtility.SerializePrefabModifications(mods, ref objs); } } finally { this.allowRegisteringScannedTypes = false; } } } } } // Load a new empty scene that will be unloaded immediately, just to be sure we completely clear all changes made by the scan EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); } finally { if (oldSceneSetup != null && oldSceneSetup.Length > 0) { if (showProgressBar) { EditorUtility.DisplayProgressBar("Restoring scene setup", "", 1.0f); } EditorSceneManager.RestoreSceneManagerSetup(oldSceneSetup); } } if (includeSceneDependencies) { for (int i = 0; i < scenePaths.Length; i++) { var scenePath = scenePaths[i]; if (showProgressBar && EditorUtility.DisplayCancelableProgressBar("Scanning scene dependencies for AOT support", "Scene " + (i + 1) + "/" + scenePaths.Length + " - " + scenePath, (float)i / scenePaths.Length)) { return(false); } string[] dependencies = AssetDatabase.GetDependencies(scenePath, recursive: true); foreach (var dependency in dependencies) { this.ScanAsset(dependency, includeAssetDependencies: false); // All dependencies of this asset were already included recursively by Unity } } } return(true); } finally { if (showProgressBar) { EditorUtility.ClearProgressBar(); } UnitySerializationUtility.ForceEditorModeSerialization = formerForceEditorModeSerialization; } }