Unity属性美化方法

以前看到插件的代码和其他人写的代码都带有一些新奇的玩意儿,嗯,特别羡慕。
然后找个时间去捣鼓一下,去翻unity manual,找到这个玩意儿。
效果:给类的公开字段添加EditorUI拉条,和只读的进度条,拉条的进度跟随字段数值改变;
涉及类:
SerializedProperty
https://docs.unity3d.com/ScriptReference/SerializedProperty.html
SerializedProperty和SerializedObject是用于以完全通用的方式编辑对象上的属性的类,可以自动处理撤销和为预置的UI设置样式。
Editor
https://docs.unity3d.com/cn/current/ScriptReference/Editor.html
从中派生自定义编辑器的基类。使用此类可为对象创建您自己的自定义检视面板和编辑器。
SerializedObject
https://docs.unity3d.com/cn/current/ScriptReference/SerializedObject.html

复制代码
using UnityEditor;
using UnityEngine;
using System.Collections;

// Custom Editor using SerializedProperties.
// Automatic handling of multi-object editing, undo, and Prefab overrides.
[CustomEditor(typeof(MyPlayer))]//指定适用于那个类
[CanEditMultipleObjects]//可以被多选操作
public class MyPlayerEditor : Editor
{
    SerializedProperty damageProp;
    SerializedProperty armorProp;
    SerializedProperty gunProp;

    void OnEnable()
    {
        // Setup the SerializedProperties.
        damageProp = serializedObject.FindProperty("damage");
        armorProp = serializedObject.FindProperty("armor");
        gunProp = serializedObject.FindProperty("gun");
    }

    public override void OnInspectorGUI()//
    {
        // Update the serializedProperty - always do this in the beginning of OnInspectorGUI.
        serializedObject.Update();

        // Show the custom GUI controls.
        EditorGUILayout.IntSlider(damageProp, 0, 100, new GUIContent("Damage"));//创建一个拉条

        // Only show the damage progress bar if all the objects have the same damage value:
        if (!damageProp.hasMultipleDifferentValues)
            ProgressBar(damageProp.intValue / 100.0f, "Damage");//创建一个只读的进度条

        EditorGUILayout.IntSlider(armorProp, 0, 100, new GUIContent("Armor"));

        // Only show the armor progress bar if all the objects have the same armor value:
        if (!armorProp.hasMultipleDifferentValues)
            ProgressBar(armorProp.intValue / 100.0f, "Armor");

        EditorGUILayout.PropertyField(gunProp, new GUIContent("Gun Object"));

        // Apply changes to the serializedProperty - always do this in the end of OnInspectorGUI.
        serializedObject.ApplyModifiedProperties();
    }

    // Custom GUILayout progress bar.
    void ProgressBar(float value, string label)
    {
        // Get a rect for the progress bar using the same margins as a textfield:
        Rect rect = GUILayoutUtility.GetRect(18, 18, "TextField");
        EditorGUI.ProgressBar(rect, value, label);
        EditorGUILayout.Space();
    }
}
复制代码
posted @   过往云烟吧  阅读(63)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示