Unity3D 自定义编辑器界面(Inspector)

今天看一个脚本,本想看看在 Inspector 界面的变量在脚本里的用途,然后查找变量名的时候怎么也找不到,自己也是惊讶。通过网上搜索才了解到原来 Inspector界面 是可以自己定义的。

当然自己定义,当然也需要写一个脚本来改的。可能是为了让界面整洁的目的。

  1. 首先,在头文件里需要添加 using UnityEditor;
  2. 新建一个文件夹 命名为 Editor 因为我们需要 using unityEditor ,而是用这个的脚本必须在名字为Editor 的文件夹下。在Editor 文件下创建一个C#新脚本 名字随意,我取名为 EditTest

假设原来物体挂的脚本名字是 Test

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{

    public int int_data;
    public float float_data;
    public Vector3 vector3_data;
    public bool bool_data;
    public Texture2D texture2d_data;

    public void PrintData()
    {
        Debug.Log("int_data=" + int_data);
        Debug.Log("float_data=" + float_data);
        Debug.Log("Vector3_data=" + vector3_data);
        Debug.Log("bool_data=" + bool_data);
    }
}

修改界面脚本为

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(Test))]  //这里Test是原来脚本的名字
public class EditTest : Editor   //继承改为Editor
{
    test test_scripts; //脚本本体
    SerializedObject serObj;//用来获取各脚本变量
    SerializedProperty int_data;
    SerializedProperty float_data;
    SerializedProperty vector3_data;
    SerializedProperty bool_data;
    SerializedProperty texture2d_data;

    /// <summary>
    /// 初始化 Objcet对象,绑定各变量, 抓取脚本里面的属性
    /// </summary>
    private void OnEnable()
    {
        test_scripts= (test)target;
        serObj = new SerializedObject(target);

        int_data = serObj.FindProperty("int_data");
        float_data = serObj.FindProperty("float_data");
        vector3_data = serObj.FindProperty("vector3_data");
        bool_data = serObj.FindProperty("bool_data");
        texture2d_data = serObj.FindProperty("texture2d_data");
    }

    /// <summary>
    /// 显示
    /// </summary>
    public override void OnInspectorGUI() //更新脚本的信息
    {
        serObj.Update();
        EditorGUILayout.LabelField("以下是各数据的设置", EditorStyles.miniLabel);
        EditorGUILayout.Separator();
        EditorGUILayout.PropertyField(int_data, new GUIContent("int_data"));
        EditorGUILayout.Slider(float_data, 0.0f, 50.0f, new GUIContent("float_data"));
        //滑动条
        EditorGUILayout.PropertyField(vector3_data, new GUIContent("vector3_data"));
        EditorGUILayout.PropertyField(bool_data, new GUIContent("bool_data"));
        EditorGUILayout.PropertyField(texture2d_data, new GUIContent("texture2d_data"));
        EditorGUILayout.EndFadeGroup();
        if (GUILayout.Button("输出信息"))
        {
            test_scripts.PrintData();
        }
        serObj.ApplyModifiedProperties(); //最后,通过此应用修改属性效果 
    }
}

效果图:

各种API接口功能在官方有解释,可查询。

https://docs.unity3d.com/ScriptReference/EditorGUILayout.html

猜你喜欢

转载自blog.csdn.net/weixin_42513339/article/details/83028790