Unity Editor中获取当前场景(包括Prefab编辑场景)中指定Component的方法

开发过程中想写个简化操作的小工具,先是用了常用的

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

解决了问题。

posted @ 2020-03-13 16:32  zs_3718  阅读(2996)  评论(0编辑  收藏  举报