private static void CreateEventSystem(bool select, GameObject parent) { StageHandle stage = parent == null?StageUtility.GetCurrentStageHandle() : StageUtility.GetStageHandle(parent); var esys = stage.FindComponentOfType <EventSystem>(); if (esys == null) { var eventSystem = new GameObject("EventSystem"); if (parent == null) { StageUtility.PlaceGameObjectInCurrentStage(eventSystem); } else { GameObjectUtility.SetParentAndAlign(eventSystem, parent); } esys = eventSystem.AddComponent <EventSystem>(); eventSystem.AddComponent <StandaloneInputModule>(); Undo.RegisterCreatedObjectUndo(eventSystem, "Create " + eventSystem.name); } if (select && esys != null) { Selection.activeGameObject = esys.gameObject; } }
private static void OnPrefabStageClosed(PrefabStage prefabStage) { if (log) { Debug.LogWarning(string.Format("Prefab stage closed, checking NGUI objects | Cameras: {0} | Panels: {1} | Drawcalls: {2}/{3}", UICamera.list.size, UIPanel.list.Count, UIDrawCall.activeList.size, UIDrawCall.inactiveList.size)); } CheckNGUIObjects(); // Since no events happened from standpoint of main stage objects, we have force them to update var stageHandleMain = StageUtility.GetMainStageHandle(); for (int s = 0; s < SceneManager.sceneCount; s++) { var sceneFromList = SceneManager.GetSceneAt(s); if (!sceneFromList.isLoaded) { continue; } var stageHandleFromList = StageUtility.GetStageHandle(sceneFromList); if (stageHandleFromList != stageHandleMain) { continue; } var sceneRootObjects = sceneFromList.GetRootGameObjects(); for (int i = 0; i < sceneRootObjects.Length; i++) { FindAndRefreshPanels(sceneRootObjects[i].transform); } } }
public void Save() { var mainStage = StageUtility.GetMainStageHandle(); var currentStage = StageUtility.GetStageHandle(gameObject); if (mainStage == currentStage) { if (PrefabUtility.IsPartOfPrefabInstance(gameObject)) { // Prefab instance var scene = SceneManager.GetActiveScene(); UpdateChanges(gameObject, AssetDatabase.LoadAssetAtPath(scene.path, typeof(SceneAsset))); } else { // Normal object in scene var scene = SceneManager.GetActiveScene(); UpdateChanges(gameObject, AssetDatabase.LoadAssetAtPath(scene.path, typeof(SceneAsset))); } } else { var prefabStage = PrefabStageUtility.GetPrefabStage(gameObject); if (prefabStage != null) { UpdateChanges(AssetDatabase.LoadAssetAtPath(prefabStage.prefabAssetPath, typeof(GameObject))); } } }
void AddCameraToCameraList(Rect rect, ReorderableList list) { StageHandle stageHandle = StageUtility.GetStageHandle(camera.gameObject); var allCameras = stageHandle.FindComponentsOfType <Camera>(); foreach (var camera in allCameras) { var component = camera.gameObject.GetComponent <UniversalAdditionalCameraData>(); if (component != null) { if (validCameraTypes.Contains(component.renderType)) { validCameras.Add(camera); } } } var names = new GUIContent[validCameras.Count]; for (int i = 0; i < validCameras.Count; ++i) { names[i] = new GUIContent(validCameras[i].name); } if (!validCameras.Any()) { names = new GUIContent[1]; names[0] = new GUIContent("No Overlay Cameras exist."); } EditorUtility.DisplayCustomMenu(rect, names, -1, AddCameraToCameraListMenuSelected, null); }
private static bool BelongsToCurrentStage(this GameObject go, PrefabStage prefabStage, StageHandle stageHandleMain) { var stageHandleFromObject = StageUtility.GetStageHandle(go); bool result = prefabStage != null ? (stageHandleFromObject == prefabStage.stageHandle) : (stageHandleFromObject == stageHandleMain); return(result); }
/// <summary> /// Returns true if the given object is being edited in prefab mode. /// </summary> /// <param name="obj">Object to check</param> /// <returns>True if object is in prefab mode</returns> public static bool IsEditingInPrefabMode(GameObject obj) { #if UNITY_EDITOR if (EditorUtility.IsPersistent(obj)) { // Stored on disk (some sort of prefab) return true; } else { #if UNITY_2018_3_OR_NEWER // If not persistent, check if in prefab stage if (StageUtility.GetMainStageHandle() != StageUtility.GetStageHandle(obj)) { var stage = PrefabStageUtility.GetPrefabStage(obj); if (stage != null) { return true; } } #endif } #endif return false; }
public EObjectStage GetObjectStage() { #if UNITY_EDITOR if (EditorUtility.IsPersistent(gameObject)) { return(EObjectStage.PRESISTENCE_STAGE); } // If the GameObject is not persistent let's determine which stage we are in first because getting Prefab info depends on it var mainStage = StageUtility.GetMainStageHandle(); var currentStage = StageUtility.GetStageHandle(gameObject); if (currentStage == mainStage) { if (PrefabUtility.IsPartOfPrefabInstance(gameObject)) { var type = PrefabUtility.GetPrefabAssetType(gameObject); var path = AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromSource(gameObject)); //Debug.Log(string.Format("GameObject is part of a Prefab Instance in the MainStage and is of type: {0}. It comes from the prefab asset: {1}", type, path)); return(EObjectStage.MAIN_STAGE); } else { //Debug.Log("GameObject is a plain GameObject in the MainStage"); return(EObjectStage.MAIN_STAGE); } } else { var prefabStage = PrefabStageUtility.GetPrefabStage(gameObject); if (prefabStage != null) { if (PrefabUtility.IsPartOfPrefabInstance(gameObject)) { var type = PrefabUtility.GetPrefabAssetType(gameObject); var nestedPrefabPath = AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromSource(gameObject)); //Debug.Log(string.Format("GameObject is in a PrefabStage. The GameObject is part of a nested Prefab Instance and is of type: {0}. The opened Prefab asset is: {1} and the nested Prefab asset is: {2}", type, prefabStage.prefabAssetPath, nestedPrefabPath)); return(EObjectStage.PREFAB_STAGE); } else { var prefabAssetRoot = AssetDatabase.LoadAssetAtPath <GameObject>(prefabStage.prefabAssetPath); var type = PrefabUtility.GetPrefabAssetType(prefabAssetRoot); //Debug.Log(string.Format("GameObject is in a PrefabStage. The opened Prefab is of type: {0}. The GameObject comes from the prefab asset: {1}", type, prefabStage.prefabAssetPath)); return(EObjectStage.PREFAB_STAGE); } } else if (EditorSceneManager.IsPreviewSceneObject(gameObject)) { //Debug.Log("GameObject is not in the MainStage, nor in a PrefabStage. But it is in a PreviewScene so could be used for Preview rendering or other utilities."); return(EObjectStage.OTHER_STAGE); } else { LogConsoleError("Unknown GameObject Info"); } } #endif return(EObjectStage.OTHER_STAGE); }
static public void PrintGameObjectInfo() { var go = Selection.activeGameObject; if (go == null) { Debug.Log("Please select a GameObject"); return; } var mainStage = StageUtility.GetMainStageHandle(); // Lets determine which stage we are in first because getting Prefab info depends on it var currentStage = StageUtility.GetStageHandle(go); if (currentStage == mainStage) { if (PrefabUtility.IsPartOfPrefabInstance(go)) { var type = PrefabUtility.GetPrefabAssetType(go); var path = AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromSource(go)); Debug.Log(string.Format("GameObject is part of a Prefab Instance in the MainStage and is of type: {0}. It comes from the prefab asset: {1}", type, path)); } else { Debug.Log("Selected GameObject is a plain GameObject in the MainStage"); } } else { var prefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetPrefabStage(go); if (prefabStage != null) { if (PrefabUtility.IsPartOfPrefabInstance(go)) { var type = PrefabUtility.GetPrefabAssetType(go); var nestedPrefabPath = AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromSource(go)); Debug.Log(string.Format("GameObject is in a PrefabStage. The GameObject is part of a nested Prefab Instance and is of type: {0}. The opened Prefab asset is: {1} and the nested Prefab asset is: {2}", type, prefabStage.prefabAssetPath, nestedPrefabPath)); } else { var prefabAssetRoot = AssetDatabase.LoadAssetAtPath <GameObject>(prefabStage.prefabAssetPath); var type = PrefabUtility.GetPrefabAssetType(prefabAssetRoot); Debug.Log(string.Format("GameObject is in a PrefabStage. The opened Prefab is of type: {0}. The GameObject comes from the prefab asset: {1}", type, prefabStage.prefabAssetPath)); } } else if (EditorSceneManager.IsPreviewSceneObject(go)) { Debug.Log("GameObject is not in the MainStage, nor in a PrefabStage. But it is in a PreviewScene so could be used for Preview rendering or other utilities."); } else { Debug.LogError("Unknown GameObject Info"); } } }
void AppendModifierVolumes(ref List <NavMeshBuildSource> sources) { //Debug.Log("AppendModifierVolumes()"); #if UNITY_EDITOR var myStage = StageUtility.GetStageHandle(gameObject); if (!myStage.IsValid()) { return; } #endif // Modifiers List <NavMeshModifierVolume> modifiers; if (m_CollectObjects == CollectObjects.Children) { modifiers = new List <NavMeshModifierVolume>(GetComponentsInChildren <NavMeshModifierVolume>()); modifiers.RemoveAll(x => !x.isActiveAndEnabled); } else { modifiers = NavMeshModifierVolume.activeModifiers; } foreach (var m in modifiers) { if ((m_LayerMask & (1 << m.gameObject.layer)) == 0) { continue; } if (!m.AffectsAgentType(m_AgentTypeID)) { continue; } #if UNITY_EDITOR if (!myStage.Contains(m.gameObject)) { continue; } #endif var mcenter = m.transform.TransformPoint(m.center); var scale = m.transform.lossyScale; var msize = new Vector3(m.size.x * Mathf.Abs(scale.x), m.size.y * Mathf.Abs(scale.y), m.size.z * Mathf.Abs(scale.z)); var src = new NavMeshBuildSource(); src.shape = NavMeshBuildSourceShape.ModifierBox; src.transform = Matrix4x4.TRS(mcenter, m.transform.rotation, Vector3.one); src.size = msize; src.area = m.area; sources.Add(src); } }
internal static bool ContainsMainStageGameObjects(GameObject[] objects) { if (objects == null || objects.Length == 0) { return(false); } for (int i = 0; i < objects.Length; i++) { if (objects[i] != null && StageUtility.GetStageHandle(objects[i]).isMainStage) { return(true); } } return(false); }
static bool IsValidCanvas(Canvas canvas) { if (canvas == null || !canvas.gameObject.activeInHierarchy) { return(false); } // It's important that the non-editable canvas from a prefab scene won't be rejected, // but canvases not visible in the Hierarchy at all do. Don't check for HideAndDontSave. if (EditorUtility.IsPersistent(canvas) || (canvas.hideFlags & HideFlags.HideInHierarchy) != 0) { return(false); } return(StageUtility.GetStageHandle(canvas.gameObject) == StageUtility.GetCurrentStageHandle()); }
static bool IsValidSolver(ObiSolver solver) { if (solver == null || !solver.gameObject.activeInHierarchy) { return(false); } if (EditorUtility.IsPersistent(solver) || (solver.hideFlags & HideFlags.HideInHierarchy) != 0) { return(false); } if (StageUtility.GetStageHandle(solver.gameObject) != StageUtility.GetCurrentStageHandle()) { return(false); } return(true); }
void FocusCamera() { var cinemachine = StageUtility.GetStageHandle(m_ControlAction.gameObject).FindComponentOfType <CinemachineFreeLook>(); if (cinemachine) { var serializedCinemachine = new SerializedObject(cinemachine); var modelGroup = m_ControlAction.GetComponentInParent <ModelGroup>(); if (modelGroup) { serializedCinemachine.FindProperty("m_LookAt").objectReferenceValue = modelGroup.transform; serializedCinemachine.FindProperty("m_Follow").objectReferenceValue = modelGroup.transform; var scopedBricks = m_ControlAction.GetScopedBricks(); var scopedBounds = m_ControlAction.GetScopedBounds(scopedBricks, out _, out _); var radius = scopedBounds.extents.magnitude; if (!cinemachine.m_Lens.Orthographic) { var cameraVerticalFOV = cinemachine.m_Lens.FieldOfView; var cameraHorizontalFOV = Camera.VerticalToHorizontalFieldOfView(cameraVerticalFOV, cinemachine.m_Lens.Aspect); var fov = Mathf.Min(cameraHorizontalFOV, cameraVerticalFOV) * 0.5f; var distance = radius / Mathf.Tan(fov * Mathf.Deg2Rad) + radius; serializedCinemachine.FindProperty("m_Orbits").GetArrayElementAtIndex(1).FindPropertyRelative("m_Radius").floatValue = distance; } else { serializedCinemachine.FindProperty("m_Lens").FindPropertyRelative("OrthographicSize").floatValue = radius; } } serializedCinemachine.ApplyModifiedProperties(); } else { EditorUtility.DisplayDialog("Cinemachine Free Look Camera Not Found", "Focus camera only supports Cinemachine Free Look camera.", "OK"); } }
static bool IsValidCanvas(Canvas canvas) { if (canvas == null || !canvas.gameObject.activeInHierarchy) { return(false); } if (EditorUtility.IsPersistent(canvas) || (canvas.hideFlags & HideFlags.HideInHierarchy) != 0) { return(false); } if (StageUtility.GetStageHandle(canvas.gameObject) != StageUtility.GetCurrentStageHandle()) { return(false); } return(true); }
public List <Trigger> GetTargetingTriggers() { var result = new List <Trigger>(); #if UNITY_EDITOR var triggers = StageUtility.GetStageHandle(gameObject).FindComponentsOfType <Trigger>(); #else var triggers = FindObjectsOfType <Trigger>(); #endif foreach (var trigger in triggers) { if (trigger.GetTargetedActions().Contains(this)) { result.Add(trigger); } } return(result); }
static void Postfix(UIPanel panel, Material mat, Texture tex, Shader shader, UIDrawCall __result) { var prefabStage = PrefabStageUtility.GetCurrentPrefabStage(); if (prefabStage != null) { if (__result.manager != null) { var stage = StageUtility.GetStageHandle(__result.manager.gameObject); if (stage == prefabStage.stageHandle) { SceneManager.MoveGameObjectToScene(__result.gameObject, prefabStage.scene); if (log) { Debug.Log(string.Format("Intercepted draw call creation for a panel in prefab stage ({0}), moving it from main stage", __result.manager.gameObject.name), __result.manager.gameObject); } } } } }
private bool IsEditingInPrefabMode() { if (EditorUtility.IsPersistent(this)) { // if the game object is stored on disk, it is a prefab of some kind, despite not returning true for IsPartOfPrefabAsset =/ return(true); } else { // If the GameObject is not persistent let's determine which stage we are in first because getting Prefab info depends on it var mainStage = StageUtility.GetMainStageHandle(); var currentStage = StageUtility.GetStageHandle(gameObject); if (currentStage != mainStage) { var prefabStage = PrefabStageUtility.GetPrefabStage(gameObject); if (prefabStage != null) { return(true); } } } return(false); }
private static void CreateEventSystem(bool select, GameObject parent) { EventSystem eventSystem = ((!(parent == null)) ? StageUtility.GetStageHandle(parent) : StageUtility.GetCurrentStageHandle()).FindComponentOfType <EventSystem>(); if (eventSystem == null) { GameObject gameObject = new GameObject("EventSystem"); if (parent == null) { StageUtility.PlaceGameObjectInCurrentStage(gameObject); } else { GameObjectUtility.SetParentAndAlign(gameObject, parent); } eventSystem = gameObject.AddComponent <EventSystem>(); gameObject.AddComponent <StandaloneInputModule>(); Undo.RegisterCreatedObjectUndo(gameObject, "Create " + gameObject.name); } if (select && eventSystem != null) { Selection.activeGameObject = eventSystem.gameObject; } }
internal bool IsInMainStage() { return(!EditorUtility.IsPersistent(gameObject) && StageUtility.GetStageHandle(gameObject) == StageUtility.GetMainStageHandle()); }
static void Postfix(GameObject __result, string prefabAssetPath, Scene previewScene) { // Handling inconvenient var names var instanceRoot = __result; var scene = previewScene; if (instanceRoot == null || scene == null) { return; } var stageHandleMain = StageUtility.GetMainStageHandle(); var rootsInPrefab = instanceRoot.GetComponentsInChildren <UIRoot>(true); var panelsInPrefab = instanceRoot.GetComponentsInChildren <UIPanel>(true); bool missingRoot = rootsInPrefab.Length == 0; bool missingPanel = panelsInPrefab.Length == 0; // If nothing is missing, there is no reason to continue if (!missingRoot && !missingPanel) { return; } GameObject container = EditorUtility.CreateGameObjectWithHideFlags("UIRoot (Environment)", HideFlags.DontSave); container.layer = LayerMask.NameToLayer("UI"); if (missingRoot) { // To maintain consistent world space scale of UI elements, it might be worth looking for existing root in main stage // If you don't need non-default root settings, it's perfectly fine to just leave a single AddComponent<UIRoot> call here var rootsInMainStage = new List <UIRoot>(); for (int s = 0; s < SceneManager.sceneCount; s++) { var sceneFromList = SceneManager.GetSceneAt(s); if (!sceneFromList.isLoaded || sceneFromList == scene) { continue; } var sceneStageHandle = StageUtility.GetStageHandle(sceneFromList); if (sceneStageHandle != stageHandleMain) { continue; } var sceneRootObjects = sceneFromList.GetRootGameObjects(); for (int j = 0; j < sceneRootObjects.Length; j++) { var go = sceneRootObjects[j]; var rootsInChildren = go.GetComponentsInChildren <UIRoot>(true); if (rootsInChildren.Length > 0) { rootsInMainStage.AddRange(rootsInChildren); } } } var rootInContainer = container.AddComponent <UIRoot>(); if (rootsInMainStage.Count > 0) { var rootInMainStage = rootsInMainStage[0]; rootInContainer.scalingStyle = rootInMainStage.scalingStyle; rootInContainer.manualWidth = rootInMainStage.manualWidth; rootInContainer.manualHeight = rootInMainStage.manualHeight; rootInContainer.minimumHeight = rootInMainStage.minimumHeight; rootInContainer.maximumHeight = rootInMainStage.maximumHeight; rootInContainer.adjustByDPI = rootInMainStage.adjustByDPI; rootInContainer.fitWidth = rootInMainStage.fitWidth; rootInContainer.fitHeight = rootInMainStage.fitHeight; rootInContainer.shrinkPortraitUI = rootInMainStage.shrinkPortraitUI; } else { rootInContainer.scalingStyle = UIRoot.Scaling.Flexible; rootInContainer.manualWidth = 1920; rootInContainer.manualHeight = 1080; rootInContainer.minimumHeight = 1920; rootInContainer.maximumHeight = 1080; rootInContainer.adjustByDPI = false; rootInContainer.fitWidth = false; rootInContainer.fitHeight = true; rootInContainer.shrinkPortraitUI = false; } } if (missingPanel) { // Default values of a panel are perfectly fine, so we are not going to go through the trouble of finding an existing one var panelInContainer = container.AddComponent <UIPanel>(); } SceneManager.MoveGameObjectToScene(container, scene); instanceRoot.transform.SetParent(container.transform, false); #if TEXTMESHPRO_SUPPORT Canvas canvas = container.AddComponent <Canvas> (); canvas.renderMode = RenderMode.ScreenSpaceOverlay; #endif }
public void LogStageInformation() { #if UNITY_EDITOR // First check if input GameObject is persistent before checking what stage the GameObject is in if (EditorUtility.IsPersistent(gameObject)) { if (!PrefabUtility.IsPartOfPrefabAsset(gameObject)) { LogConsole("The GameObject is a temporary object created during import. OnValidate() is called two times with a temporary object during import: First time is when saving cloned objects to .prefab file. Second event is when reading .prefab file objects during import"); } else { LogConsole("GameObject is part of an imported Prefab Asset (from the Library folder)"); } return; } // If the GameObject is not persistent let's determine which stage we are in first because getting Prefab info depends on it var mainStage = StageUtility.GetMainStageHandle(); var currentStage = StageUtility.GetStageHandle(gameObject); if (currentStage == mainStage) { if (PrefabUtility.IsPartOfPrefabInstance(gameObject)) { var type = PrefabUtility.GetPrefabAssetType(gameObject); var path = AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromSource(gameObject)); LogConsole(string.Format("GameObject is part of a Prefab Instance in the MainStage and is of type: {0}. It comes from the prefab asset: {1}", type, path)); } else { LogConsole("GameObject is a plain GameObject in the MainStage"); } } else { var prefabStage = PrefabStageUtility.GetPrefabStage(gameObject); if (prefabStage != null) { if (PrefabUtility.IsPartOfPrefabInstance(gameObject)) { var type = PrefabUtility.GetPrefabAssetType(gameObject); var nestedPrefabPath = AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromSource(gameObject)); LogConsole(string.Format("GameObject is in a PrefabStage. The GameObject is part of a nested Prefab Instance and is of type: {0}. The opened Prefab asset is: {1} and the nested Prefab asset is: {2}", type, prefabStage.prefabAssetPath, nestedPrefabPath)); } else { var prefabAssetRoot = AssetDatabase.LoadAssetAtPath <GameObject>(prefabStage.prefabAssetPath); var type = PrefabUtility.GetPrefabAssetType(prefabAssetRoot); LogConsole(string.Format("GameObject is in a PrefabStage. The opened Prefab is of type: {0}. The GameObject comes from the prefab asset: {1}", type, prefabStage.prefabAssetPath)); } } else if (EditorSceneManager.IsPreviewSceneObject(gameObject)) { LogConsole("GameObject is not in the MainStage, nor in a PrefabStage. But it is in a PreviewScene so could be used for Preview rendering or other utilities."); } else { LogConsole("Unknown GameObject Info"); } } #endif }
// UnityEditor.UI.MenuOptions private static bool IsValidCanvas(Canvas canvas) { return(!(canvas == null) && canvas.gameObject.activeInHierarchy && !EditorUtility.IsPersistent(canvas) && (canvas.hideFlags & HideFlags.HideInHierarchy) == HideFlags.None && !(StageUtility.GetStageHandle(canvas.gameObject) != StageUtility.GetCurrentStageHandle())); }
public virtual void OnOverlayGUI(Object target, SceneView sceneView) { if (target == null) { return; } var c = (Camera)target; // Do not render the Camera Preview overlay if the target camera is not part of the stage the SceneView is rendering var targetStage = StageUtility.GetStageHandle(c.gameObject); var sceneViewStage = StageUtility.GetStageHandle(sceneView.customScene); if (targetStage != sceneViewStage) { return; } Vector2 previewSize = c.targetTexture ? new Vector2(c.targetTexture.width, c.targetTexture.height) : GameView.GetMainGameViewTargetSize(); if (previewSize.x < 0f) { // Fallback to Scene View of not a valid game view size previewSize.x = sceneView.position.width; previewSize.y = sceneView.position.height; } // Apply normalizedviewport rect of camera Rect normalizedViewPortRect = c.rect; // clamp normalized rect in [0,1] normalizedViewPortRect.xMin = Math.Max(normalizedViewPortRect.xMin, 0f); normalizedViewPortRect.yMin = Math.Max(normalizedViewPortRect.yMin, 0f); normalizedViewPortRect.xMax = Math.Min(normalizedViewPortRect.xMax, 1f); normalizedViewPortRect.yMax = Math.Min(normalizedViewPortRect.yMax, 1f); previewSize.x *= Mathf.Max(normalizedViewPortRect.width, 0f); previewSize.y *= Mathf.Max(normalizedViewPortRect.height, 0f); // Prevent using invalid previewSize if (previewSize.x < 1f || previewSize.y < 1f) { return; } float aspect = previewSize.x / previewSize.y; // Scale down (fit to scene view) previewSize.y = kPreviewNormalizedSize * sceneView.position.height; previewSize.x = previewSize.y * aspect; if (previewSize.y > sceneView.position.height * 0.5f) { previewSize.y = sceneView.position.height * 0.5f; previewSize.x = previewSize.y * aspect; } if (previewSize.x > sceneView.position.width * 0.5f) { previewSize.x = sceneView.position.width * 0.5f; previewSize.y = previewSize.x / aspect; } // Get and reserve rect Rect cameraRect = GUILayoutUtility.GetRect(previewSize.x, previewSize.y); if (Event.current.type == EventType.Repaint) { // setup camera and render previewCamera.CopyFrom(c); // make sure the preview camera is rendering the same stage as the SceneView is previewCamera.scene = sceneView.customScene; // also make sure to sync any Skybox component on the preview camera var dstSkybox = previewCamera.GetComponent <Skybox>(); if (dstSkybox) { var srcSkybox = c.GetComponent <Skybox>(); if (srcSkybox && srcSkybox.enabled) { dstSkybox.enabled = true; dstSkybox.material = srcSkybox.material; } else { dstSkybox.enabled = false; } } var previewTexture = GetPreviewTextureWithSize((int)cameraRect.width, (int)cameraRect.height); previewTexture.antiAliasing = Mathf.Max(1, QualitySettings.antiAliasing); previewCamera.targetTexture = previewTexture; previewCamera.pixelRect = new Rect(0, 0, cameraRect.width, cameraRect.height); Handles.EmitGUIGeometryForCamera(c, previewCamera); if (c.usePhysicalProperties) { // when sensor size is reduced, the previous frame is still visible behing so we need to clear the texture before rendering. RenderTexture rt = RenderTexture.active; RenderTexture.active = previewTexture; GL.Clear(false, true, Color.clear); RenderTexture.active = rt; } previewCamera.Render(); Graphics.DrawTexture(cameraRect, previewTexture, new Rect(0, 0, 1, 1), 0, 0, 0, 0, GUI.color, EditorGUIUtility.GUITextureBlit2SRGBMaterial); } }
/// <summary> /// Returns the environment this GameObject exists in. /// </summary> public static GameObjectEnvironments GetGameObjectEnvironment(this GameObject gameObject) { //based on https://github.com/Unity-Technologies/PrefabAPIExamples/blob/master/Assets/Scripts/GameObjectTypeLogging.cs //most comments also from there GameObjectEnvironments environment; #if UNITY_EDITOR //check if game object exists on disk if (EditorUtility.IsPersistent(gameObject)) { if (!PrefabUtility.IsPartOfPrefabAsset(gameObject)) { //The GameObject is a temporary object created during import. //OnValidate() is called two times with a temporary object during import: // First time is when saving cloned objects to .prefab file. // Second event is when reading .prefab file objects during import environment = GameObjectEnvironments.PrefabImport; } else { //GameObject is part of an imported Prefab Asset (from the Library folder) environment = GameObjectEnvironments.PrefabAsset; } } else { //If the GameObject is not persistent let's determine which stage we are in first because getting Prefab info depends on it StageHandle mainStage = StageUtility.GetMainStageHandle(); StageHandle currentStage = StageUtility.GetStageHandle(gameObject); if (currentStage == mainStage) { //viewing scenes in the main stage (aka -not- editing in prefab mode) if (PrefabUtility.IsPartOfPrefabInstance(gameObject)) { //GameObject is part of a Prefab Instance in the MainStage environment = GameObjectEnvironments.PrefabInstance; } else { //GameObject is a plain GameObject in the MainStage environment = GameObjectEnvironments.Scene; } } else { //editing a prefab in prefab mode PrefabStage prefabStage = PrefabStageUtility.GetPrefabStage(gameObject); if (prefabStage != null) { if (PrefabUtility.IsPartOfPrefabInstance(gameObject)) { //GameObject is in a PrefabStage and is nested. environment = GameObjectEnvironments.NestedPrefabStage; } else { //GameObject is in a PrefabStage. environment = GameObjectEnvironments.PrefabStage; } } else if (EditorSceneManager.IsPreviewSceneObject(gameObject)) { //GameObject is not in the MainStage, nor in a PrefabStage. //But it is in a PreviewScene so could be used for Preview rendering or other utilities. environment = GameObjectEnvironments.PreviewScene; } else { //Unknown GameObject Info environment = GameObjectEnvironments.Unknown; } } } #else //Can't do any of the above checks outside of the editor environment = GameObjectEnvironments.Unknown; #endif return(environment); }