天天看點

unity編輯器擴充篇-中文字段顯示編輯器擴充篇-中文字段顯示

編輯器擴充篇-中文字段顯示

因為unity原生編輯器或多或少不滿足業務需求或使用者的審美,我常常需要對編輯器進行擴充。這不,我很不滿unity原生字段在inspect面闆的顯示,希望字段能以中文方式顯示字段,unity編輯器擴充這一強大的功能給了我任性的需求提供了解決之道。

隻有使用過unity的都清楚你在類中定義怎樣的字段屬性,inspect面闆上顯示的字段屬性就是你用英文描述的字段。可我就是把這個字段以中文方式啊,怎麼辦?

unity編輯器擴充篇-中文字段顯示編輯器擴充篇-中文字段顯示

我的解決方法是自定義一個特性,利用這個特性擷取你希望這個字段顯示的中文字元串,然後利用PropertyDrawer在inspectt面闆重新字段的label即可。

使用

unity編輯器擴充篇-中文字段顯示編輯器擴充篇-中文字段顯示
/// <summary>
    /// 技能
    /// </summary>
    [Serializable]
    public class Skill : ScriptableObject
    {

        [SerializeField][FieldLabel("技能名稱")]
        private string sname;
        [SerializeField][FieldLabel("技能類别")]
        private SkillType type;
        [SerializeField][FieldLabel("威力")]
        private int power;//威力
        [SerializeField][FieldLabel("命中率")]
        private int hitRate;//命中率
        [SerializeField][FieldLabel("pp值")]
           

我這裡例子是scriptableObject,普通public類是一樣的

public class Test: MonoBehaviour {

    [FieldLabel("技能")]
    public int a;


}
           

代碼實作

/// <summary>
/// 能讓字段在inspect面闆顯示中文字元
/// </summary>
[AttributeUsage( AttributeTargets.Field)]
public class FieldLabelAttribute : PropertyAttribute
{
    public string label;//要顯示的字元
    public FieldLabelAttribute(string label)
    {
        this.label = label;
        //擷取你想要繪制的字段(比如"技能")
    }

}

//綁定特性描述類
[CustomPropertyDrawer(typeof(FieldLabelAttribute))]
public class FieldLabelDrawer: PropertyDrawer
{
    private FieldLabelAttribute FLAttribute
    {
        get { return (FieldLabelAttribute)attribute; }
        ////擷取你想要繪制的字段
    }
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        //在這裡重新繪制
        EditorGUI.PropertyField(position, property, new GUIContent(FLAttribute.label), true);

    } 
}