Unity在非激活場景中創建GameObject

本文地址:https://blog.csdn.net/t163361/article/details/105234184
直接通過 var go = new GameObject(); 這樣的方式創建的物體都會創建在已經激活的場景裏面
如果想直接在一個特定場景創建的話,可以使用
EditorSceneManager.SetTargetSceneForNewGameObjects()
這個方法
創建之前通過設置對應的場景id,創建完成後,記得要重新設置爲0
官方SceneHierarchy.cs中有兩個私有函數就是實現相應功能的

        void BeforeCreateGameObjectMenuItemWasExecuted(string menuPath, UnityEngine.Object[] contextObjects, int userData)
        {
            int sceneHandle = userData;
            EditorSceneManager.SetTargetSceneForNewGameObjects(sceneHandle);
        }

        void AfterCreateGameObjectMenuItemWasExecuted(string menuPath, UnityEngine.Object[] contextObjects, int userData)
        {
            EditorSceneManager.SetTargetSceneForNewGameObjects(kInvalidSceneHandle);

            // Ensure framing when creating game objects even if we are locked
            if (isLocked)
                m_FrameOnSelectionSync = true;
        }

先調用BeforeCreateGameObjectMenuItemWasExecuted
對象創建完成後調用
AfterCreateGameObjectMenuItemWasExecuted

不過上面的函數都是private或者內部的,需要自己反射調用

上面函數只能在編輯器中用

MoveGameObjectToScene這個函數可以把創建好的對象移動到指定場景中,這算一個通用的辦法了,就是還需要多轉換一下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章