首页 > 技术文章 > 开坑UnityEditor

Mr147 2020-07-15 17:57 原文

首先

开始学习UnityEditor,记录一下
编辑器扩展这部分东西以前还是不太想碰的,感觉东西又多又难,但目前需要来做一些自定义插件,提升效率,走起!
先贴一下官方的UnityEditor API:https://docs.unity3d.com/ScriptReference/UnityEditor.html

动手

咱们先来个最基本的
所有编辑器扩展的东西都要放在叫Editor的文件夹下面
编辑器扩展要对用一个Mono组件,首先定义一个MonoBehavior

using UnityEngine;

public class Test1 : MonoBehaviour
{

    public string name;
    public int id;
    public Vector3 pos;
    public GameObject box;

    private void Start()
    {
        Debug.Log(name);
    }
}

然后对应一个编辑器扩展组件,要引用using UnityEditor,并且继承Editor类

using UnityEngine;
using UnityEditor;

//绑定Test1
[CustomEditor(typeof(Test1))]
public class EditorTest1 : Editor
{
    //声明一个序列化成员box
    SerializedProperty mBox;

    public override void OnInspectorGUI()
    {
        //得到Test1对象
        Test1 mTarget = (Test1)target;

        //给mBox赋值
        mBox = serializedObject.FindProperty("box");

        //绘制参数
        mTarget.name = EditorGUILayout.TextField("Name", mTarget.name);
        //空行
        GUILayout.Space(10);
        mTarget.id = EditorGUILayout.IntField("id",mTarget.id);
        GUILayout.Space(10);
        //标签
        GUILayout.Label("Box");
        //绘制box赋值,GUILayout可以绘制样式
        EditorGUILayout.PropertyField(mBox, new GUIContent("box"), GUILayout.Height(40));
    }
}

推荐阅读