有这个需求的原因是,在编辑器的Inspector 逻辑中,写了许多生成逻辑。

现在不想挨个在Inspector 上都点一遍按钮,所以就需要能获取到它们的编辑器对象。

发现可以借助官方的UnityEditor.Editor.CreateEditor 方法达到目的,如下:

public static TEditor GetEditorObjByRuntimeObj(UnityEngine.Object runtimeObj) where TEditor : UnityEditor.Editor{var editorType = typeof(TEditor);var editorObj = UnityEditor.Editor.CreateEditor(runtimeObj, editorType) as TEditor;return editorObj;}

如果我们想扩展 Unity 的原生组件,也可以借助这个方法来实现。

[CustomEditor(typeof(Transform))]public class TransformExt : Editor{private Editor m_editor;void OnEnable(){var assembly = Assembly.GetAssembly(typeof(Editor));var type = assembly.GetType("UnityEditor.TransformInspector", true);m_editor = Editor.CreateEditor(target, type);}public override void OnInspectorGUI(){// base.OnInspectorGUI();// 调用系统绘制方法m_editor.OnInspectorGUI();GUILayout.Space(5);if (GUILayout.Button("拓展按钮")){}}}

效果如图: