十二、编辑器开发之Slider及各类字段绘制

2022-08-29 15:39:28 浏览数 (1)

为测试脚本Test类中添加以下字段:

代码语言:javascript复制
using UnityEngine;

public class Test : MonoBehaviour
{
    public enum TestEnum
    {
        Enum1,
        Enum2,
    }
    public string stringValue = "str";
    public int intValue = 30;
    public float floatValue = 50f;
    public AudioClip clipValue;
    public string passwordValue = "1a2s3xd455";
    public TestEnum EnumValue = TestEnum.Enum1;
}

创建Test类的编辑器类TestEditor

1.滑动条

代码语言:javascript复制
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(Test))]
public class TestEditor : Editor
{
    private Test Target;
    private void OnEnable()
    {
        Target = target as Test;
    }

    public override void OnInspectorGUI()
    {
        //绘制Int类型滑动条
        int newIntValue = EditorGUILayout.IntSlider("Int Value", Target.intValue, 0, 30);
        if (newIntValue != Target.intValue)
        {
            Target.intValue = newIntValue;
        }
        //绘制Float类型滑动条
        float newFloatValue = EditorGUILayout.Slider("Float Value", Target.floatValue, 0f, 100f);
        if (newFloatValue != Target.floatValue)
        {
            Target.floatValue = newFloatValue;
        }
    }
}

2.各类字段:

代码语言:javascript复制
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(Test))]
public class TestEditor : Editor
{
    private Test Target;
    private void OnEnable()
    {
        Target = target as Test;
    }

    public override void OnInspectorGUI()
    {
        //绘制String类型字段
        string newStringValue = EditorGUILayout.TextField("String Value", Target.stringValue);
        if (newStringValue != Target.stringValue)
        {
            Target.stringValue = newStringValue;
        }
        //绘制Int类型字段
        int newIntValue = EditorGUILayout.IntField("Int Value", Target.intValue);
        if (newIntValue != Target.intValue)
        {
            Target.intValue = newIntValue;
        }
        //绘制Float类型字段
        float newFloatValue = EditorGUILayout.FloatField("Float Value", Target.floatValue);
        if (newFloatValue != Target.floatValue)
        {
            Target.floatValue = newFloatValue;
        }
        //绘制Object类型字段 通过as转化为其它类型
        AudioClip newClipValue = EditorGUILayout.ObjectField("AudioClip Value", Target.clipValue, typeof(AudioClip), false) as AudioClip;
        if (newClipValue != Target.clipValue)
        {
            Target.clipValue = newClipValue;
        }
        //绘制密文类型的String字段
        string newPasswordValue = EditorGUILayout.PasswordField("Password Value", Target.passwordValue);
        if(newPasswordValue != Target.passwordValue)
        {
            Target.passwordValue = newPasswordValue;
        }
        //绘制枚举类型字段
        Test.TestEnum newEnumValue = (Test.TestEnum)EditorGUILayout.EnumPopup("Enum Value", Target.EnumValue);
        if (newEnumValue != Target.EnumValue)
        {
            Target.EnumValue = newEnumValue;
        }
    }
}

0 人点赞