Unity编辑器开发(一):准备工作

前言

其实,说到Unity的编辑器开发,最大的用途就是用来开发一些实用工具或者说是插件,所涉及到的基本知识也就是Unity最早期的GUI系统的运用,只要对GUI系统运用得炉火纯青,那将自己的工具或者插件做到一流水准也不是不可以的。

编辑器的扩展开发,其实最基本的便是掌握对如下三个方法的扩展和使用:
1、UnityEditor.Editor.OnInspectorGUI()
2、UnityEditor.Editor.OnSceneGUI()
3、UnityEditor.EditorWindow.OnGUI()

OnInspectorGUI

组件的Inspector窗口GUI显示方法,调用时机:组件挂载的物体被选中,且界面重新绘制时系统自动调用。

重写自定义组件的Inspector界面

例:TestEditor类继承至Editor,指向的自定义组件为Test类(由CustomEditor特性指向),则TestEditor重写父类的OnInspectorGUI方法之后,OnInspectorGUI中的内容(主要是GUI控件)将做为Test类在场景挂载后在Inspector窗口的展示界面。

注意:TestEditor.cs必须放在Editor文件夹内,Test.cs随意。
这里写图片描述

代码:

[CustomEditor(typeof(Test))]
public class TestEditor : Editor {

    public override void OnInspectorGUI()
    {
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("This is a test!");
        EditorGUILayout.EndHorizontal();
    }
}

在场景中选择任意物体挂载Test脚本,选中这个物体,查看Test脚本的Inspector窗口:
这里写图片描述

在界面中显示或更新数据

例:每一个TestEditor类的实例,持有一个Test类的实例(其实就是挂载在场景中的当前选中的物体上的Test组件),在TestEditor类中获取Test类的实例,只需要调用一个从父类继承来的属性,target。

代码:

public class Test : MonoBehaviour
{
    public string Value = "This is a test!";
}
[CustomEditor(typeof(Test))]
public class TestEditor : Editor {

    private Test _test;

    private void OnEnable()
    {
        _test = target as Test;
    }
    public override void OnInspectorGUI()
    {
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label(_test.Value);
        EditorGUILayout.EndHorizontal();
    }
}

在场景中选择任意物体挂载Test脚本,选中这个物体,查看Test脚本的Inspector窗口:
这里写图片描述

OnSceneGUI

组件的Scene窗口扩展显示方法,调用时机:组件挂载的物体被选中,且界面重新绘制时系统自动调用。

扩展自定义组件的Scene界面

OnSceneGUI方法中主要使用Handles系列来绘制可视化调试控件,比如线、盒子、球体、文本等。

代码:

    public void OnSceneGUI()
    {
        Handles.Label(_test.transform.position, "This is a test!");
    }

在场景中选择任意物体挂载Test脚本,选中这个物体,查看Scene窗口:
这里写图片描述

OnGUI

自定义EditorWindow的GUI显示方法,调用时机:EditorWindow界面重绘时系统自动调用。

例:新建TestWindow类,继承至EditorWindow,在TestWindow类中实现OnGUI方法。

注意:TestWindow.cs必须放在Editor文件夹内。
这里写图片描述

代码:

public class TestWindow : EditorWindow {

    //注册方法到标题栏:Window/TestWindow
    [MenuItem("Window/TestWindow")]
    private static void Open()
    {
        TestWindow test = GetWindow<TestWindow>();
        test.Show();
    }

    private void OnGUI()
    {
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("This is a test window!");
        EditorGUILayout.EndHorizontal();
    }
}

点击标题栏Window/TestWindow选项,打开一个新的自定义窗口:
这里写图片描述

这里写图片描述

接下来,我们所有的扩展开发很可能都只在这三个方法中进行。

猜你喜欢

转载自blog.csdn.net/qq992817263/article/details/79292443
今日推荐