/// <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;
		}
예제 #2
0
    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);
            }
        }
    }
예제 #3
0
    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)));
            }
        }
    }
예제 #4
0
        static void OnPrefabStageClosing(PrefabStage stage)
        {
            // When closing, we want the bricks that are in the scene
            var bricks = StageUtility.GetMainStageHandle().FindComponentsOfType <Brick>();

            SetShowBricks(showAllBricks, bricks);
        }
예제 #5
0
        internal void CleanupEditor()
        {
            bool selectAvatarAsset = StageUtility.GetCurrentStageHandle() == StageUtility.GetMainStageHandle();

            m_EditMode = EditMode.Stopping;

            DestroyEditor();

            ChangeInspectorLock(m_InspectorLocked);

            EditorApplication.CallbackFunction CleanUpOnDestroy = null;
            CleanUpOnDestroy = () =>
            {
                // 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 -= CleanUpOnDestroy;
            };

            EditorApplication.update += CleanUpOnDestroy;

            // Reset back the Edit Mode specific states (they probably should be better encapsulated)
            m_GameObject = null;
            m_ModelBones = null;
        }
예제 #6
0
        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);
        }
#pragma warning disable IDE0051 // Remove unused private members -- Editor Menu Item
        static void CreateXRUICanvas(MenuCommand menuCommand)
#pragma warning restore IDE0051
        {
            var parentOfNewGameObject = menuCommand.GetContextTransform();

            var editingPrefabStage = (StageUtility.GetCurrentStageHandle() != StageUtility.GetMainStageHandle());

            var canvasGO = CreateAndPlaceGameObject("Canvas", parentOfNewGameObject,
                                                    typeof(Canvas),
                                                    typeof(CanvasScaler),
                                                    typeof(GraphicRaycaster),
                                                    typeof(TrackedDeviceGraphicRaycaster));

            // Either inherit the layer of the parent object, or use the same default that GameObject/UI/Canvas uses.
            if (parentOfNewGameObject == null)
            {
                Undo.RegisterCompleteObjectUndo(canvasGO, "Change Layer");
                canvasGO.layer = LayerMask.NameToLayer(k_UILayerName);
            }

            var canvas = canvasGO.GetComponent <Canvas>();

            Undo.RecordObject(canvas, "Configure Canvas");
            canvas.renderMode = RenderMode.WorldSpace;

            if (!editingPrefabStage)
            {
                canvas.worldCamera = Camera.main;
            }
            else
            {
                Debug.LogWarning("You have just added an XR UI Canvas to a prefab." +
                                 $" To function properly with an {nameof(XRRayInteractor)}, you must also set the Canvas component's worldCamera field in your scene.",
                                 canvasGO);
            }

            // Ensure there is at least one EventSystem setup properly
            var inputModule = Object.FindObjectOfType <XRUIInputModule>();

            if (inputModule == null)
            {
                if (!editingPrefabStage)
                {
                    CreateXRUIEventSystem(menuCommand);
                }
                else
                {
                    Debug.LogWarning("You have just added an XR UI Canvas to a prefab." +
                                     $" To function properly with an {nameof(XRRayInteractor)}, you must also add an XR UI EventSystem to your scene.",
                                     canvasGO);
                }
            }

            // May need to set this again since creating the XR UI EventSystem would have overwritten this
            Undo.SetCurrentGroupName("Create " + canvasGO.name);
            Selection.activeGameObject = canvasGO;
        }
예제 #8
0
    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");
            }
        }
    }
예제 #9
0
     public static CSGNode[] GetNodesInPrefabMode()
     {
 #if UNITY_2018_3_OR_NEWER && UNITY_EDITOR
         var mainStage          = StageUtility.GetMainStageHandle();
         var currentStageHandle = StageUtility.GetCurrentStageHandle();
         if (mainStage != currentStageHandle)
         {
             return(currentStageHandle.FindComponentsOfType <CSGNode>());
         }
 #endif
         return(null);
     }
예제 #10
0
     public static bool AreInPrefabMode()
     {
 #if UNITY_2018_3_OR_NEWER && UNITY_EDITOR
         var mainStage          = StageUtility.GetMainStageHandle();
         var currentStageHandle = StageUtility.GetCurrentStageHandle();
         if (mainStage != currentStageHandle)
         {
             return(true);
         }
 #endif
         return(false);
     }
예제 #11
0
    private static void CheckNGUIObjects()
    {
        // var root = prefabStage.prefabContentsRoot;
        // var scene = prefabStage.scene;

        var stageHandleMain = StageUtility.GetMainStageHandle();
        var prefabStage     = PrefabStageUtility.GetCurrentPrefabStage();

        for (int i = UICamera.list.size - 1; i >= 0; --i)
        {
            UICamera cam = UICamera.list[i];
            if (cam == null || !cam.gameObject.BelongsToCurrentStage(prefabStage, stageHandleMain))
            {
                UICamera.list.RemoveAt(i);
                if (log)
                {
                    Debug.Log(string.Format("Removing {0} entry {1} from the camera list", cam == null ? "a null" : "an out of stage", i));
                }
            }
        }

        for (int i = UIPanel.list.Count - 1; i >= 0; --i)
        {
            UIPanel panel = UIPanel.list[i];
            if (panel == null || !panel.gameObject.BelongsToCurrentStage(prefabStage, stageHandleMain))
            {
                UIPanel.list.RemoveAt(i);
                if (log)
                {
                    Debug.Log(string.Format("Removing {0} entry {1} from the panel list", panel == null ? "a null" : "an out of stage", i));
                }
            }
        }

        TrimDrawCalls(prefabStage, stageHandleMain, UIDrawCall.activeList, "active");
        TrimDrawCalls(prefabStage, stageHandleMain, UIDrawCall.inactiveList, "inactive");

        if (log)
        {
            Debug.LogWarning(string.Format("Recheck finished | Cameras: {0} | Panels: {1} | Drawcalls: {2}/{3}",
                                           UICamera.list.size, UIPanel.list.Count, UIDrawCall.activeList.size, UIDrawCall.inactiveList.size));
        }

        // Draw calls are not automatically restored on exit from prefab stage otherwise
        for (int i = 0; i < UIPanel.list.Count; ++i)
        {
            UIPanel.list[i].RebuildAllDrawCalls();
        }
    }
예제 #12
0
        static Scene GetLastRootScene()
        {
            if (StageUtility.GetCurrentStageHandle() == StageUtility.GetMainStageHandle())
            {
                for (int i = SceneManager.sceneCount - 1; i >= 0; i--)
                {
                    var scene = SceneManager.GetSceneAt(i);
                    if (scene.isLoaded && !scene.isSubScene)
                    {
                        return(scene);
                    }
                }
            }

            return(default);
예제 #13
0
    static bool UpdateSceneViewSkybox()
    {
        if (StageUtility.GetCurrentStageHandle() != StageUtility.GetMainStageHandle())
        {
            return(false);
        }

        SceneView sceneView = SceneView.lastActiveSceneView;

        if (sceneView == null)
        {
            return(false);
        }

        SceneView.SceneViewState state = sceneView.sceneViewState;
        state.showSkybox         = false;
        sceneView.sceneViewState = state;

        return(true);
    }
예제 #14
0
 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);
 }
예제 #15
0
        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
        }
예제 #16
0
 bool ShouldPerformChunkUpdate()
 => Application.IsPlaying(gameObject) || StageUtility.GetCurrentStageHandle() == StageUtility.GetMainStageHandle();
예제 #17
0
        /// <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);
        }
예제 #18
0
        /// <summary>
        /// Coroutine to import GLTF files with Piglet's EditorGltfImporter.
        /// The string value returned via the IEnumerator is the target directory
        /// for the current import, so that files from an aborted/canceled import
        /// can be easily cleaned up.
        /// </summary>
        private static IEnumerator <string> ImportCoroutine(List <string> gltfPaths, string baseImportDir)
        {
            foreach (string gltfPath in gltfPaths)
            {
                string gltfBasename      = Path.GetFileName(gltfPath);
                string gltfBasenameNoExt = Path.GetFileNameWithoutExtension(gltfPath);

                bool abortImport = false;

                // callback for updating progress during glTF import
                void OnProgress(GltfImportStep type, int count, int total)
                {
                    ProgressLog.Instance.OnImportProgress(type, count, total);

                    abortImport = EditorUtility.DisplayCancelableProgressBar(
                        $"Importing {gltfBasename}...",
                        ProgressLog.Instance.GetProgressMessage(),
                        (float)count / total);
                }

                string importPath = UnityPathUtil.NormalizePathSeparators(
                    Path.Combine(baseImportDir, gltfBasenameNoExt));
                string importProjectPath = UnityPathUtil.GetProjectPath(importPath);

                if ((Directory.Exists(importPath) || File.Exists(importPath)) &&
                    _pigletOptions.PromptBeforeOverwritingFiles)
                {
                    if (!EditorUtility.DisplayDialog(
                            "Warning!",
                            $"Overwrite \"{importProjectPath}\"?",
                            "OK", "Cancel"))
                    {
                        yield break;
                    }

                    FileUtil.DeleteFileOrDirectory(importPath);
                    AssetDatabase.Refresh();
                }

                GltfImportTask importTask =
                    EditorGltfImporter.GetImportTask(gltfPath, importPath,
                                                     _pigletOptions.ImportOptions);

                importTask.OnProgress = OnProgress;

                GameObject importedPrefab = null;
                importTask.OnCompleted = (prefab) => importedPrefab = prefab;

                // restart import timer at zero
                ProgressLog.Instance.StartImport();

                while (true)
                {
                    if (abortImport)
                    {
                        importTask.Abort();
                        EditorUtility.ClearProgressBar();
                        yield break;
                    }

                    try
                    {
                        if (!importTask.MoveNext())
                        {
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogException(e);

                        EditorUtility.ClearProgressBar();
                        EditorUtility.DisplayDialog("Import Failed",
                                                    String.Format("Import of {0} failed. "
                                                                  + "See Unity console log for details.", gltfBasename),
                                                    "OK");

                        yield break;
                    }

                    yield return(importPath);
                }

                // Before modifying the selection, store a handle to
                // the transform of the currently selected game object (if any).

                Transform selectedTransform = Selection.activeTransform;

                // Select the prefab file in the Project Browser.
                if (_pigletOptions.SelectPrefabAfterImport)
                {
                    Selection.activeObject = importedPrefab;
                    yield return(importPath);
                }

                if (_pigletOptions.AddPrefabToScene)
                {
                    // If we are currently in Prefab Mode, exit
                    // back to the main scene hierarchy view.
                    //
                    // Note: Prefab Mode was introduced in Unity 2018.3.
#if UNITY_2018_3_OR_NEWER
                    if (StageUtility.GetCurrentStageHandle()
                        != StageUtility.GetMainStageHandle())
                    {
                        StageUtility.GoToMainStage();
                    }
#endif

                    GameObject instance = (GameObject)PrefabUtility
                                          .InstantiatePrefab(importedPrefab);

                    // parent the prefab instance to the currently
                    // selected GameObject (if any)
                    if (selectedTransform != null)
                    {
                        instance.transform.parent = selectedTransform;
                    }

                    if (_pigletOptions.SelectPrefabInScene)
                    {
                        Selection.activeGameObject = instance;
                        yield return(importPath);
                    }
                }

                if (_pigletOptions.OpenPrefabAfterImport)
                {
                    AssetDatabase.OpenAsset(importedPrefab);

                    // Note: This is the best method I could find
                    // for automatically centering the prefab in
                    // the scene view. For further info, see
                    // https://answers.unity.com/questions/813814/framing-objects-via-script-in-the-unity-editor.html
                    SceneView.FrameLastActiveSceneView();
                }

                EditorUtility.ClearProgressBar();
            }
        }
예제 #19
0
 internal bool IsInMainStage()
 {
     return(!EditorUtility.IsPersistent(gameObject) && StageUtility.GetStageHandle(gameObject) == StageUtility.GetMainStageHandle());
 }
예제 #20
0
        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
        }