うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】Text の中身を編集できる Attribute

セットした Text の中身を書き換えられたら便利なことがたまにあると思い作成してみました

f:id:hacchi_man:20210112005523p:plain:w300

使い方

using UnityEngine;
using UnityEngine.UI;
 
public class SampleMonoBehaviour : MonoBehaviour
{
    [SerializeField, Text]
    private Text _text;
}

コード

using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
 
[AttributeUsage(AttributeTargets.Field)]
public class TextAttribute : PropertyAttribute
{
}
 
[CustomPropertyDrawer(typeof(TextAttribute))]
public class TextDrawer : PropertyDrawer
{
    private Text _cache;
 
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        if (_cache == null && property.objectReferenceValue != null)
        {
            _cache = property.objectReferenceValue as Text;
        }
 
        if (_cache == null)
        {
            EditorGUI.PropertyField(position, property, label);
            return;
        }
 
        position.height = base.GetPropertyHeight(property, label);
        EditorGUI.PropertyField(position, property, label);
        position.xMin += 10;
        position.y += position.height;
        using (var check = new EditorGUI.ChangeCheckScope())
        {
            _cache.text = EditorGUI.TextField(position, "Text", _cache.text);
            if (check.changed)
            {
                EditorUtility.SetDirty(_cache);
            }
        }
    }
 
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        if (_cache == null)
            return base.GetPropertyHeight(property, label);
 
        return base.GetPropertyHeight(property, label) * 2;
    }
}