開發過程中想寫個簡化操作的小工具,先是用了常用的
Object.FindObjectsOfType
結果發現在編輯Prefab時獲取到的也是之前打開的場景里的信息。
簡單搜了一下沒找到解決辦法,於是想着還是得去看看官方API文檔,果然找到了答案,網頁里有這么一句話:
In Editor, this searches the Scene view by default. If you want to find an object in the Prefab stage, see the StageUtility APIs
再查看StageUtility的文檔,發現有這么兩個方法:
GetCurrentStageHandle Get the current stage being edited.
GetMainStageHandle Get the main stage which contains all the currently open regular Scenes.
經過測試,上面方法是獲取當前正在編輯的場景(包括Prefab),下面的方法是獲取主場景,就是在Prefab編輯場景下獲得的也是外面打開的普通場景。
最終使用
UnityEditor.SceneManagement.StageUtility.GetCurrentStageHandle().FindComponentsOfType
解決了問題。