パハットノート

主にUnity(C#)を中心としたプログラムの備忘録

Unity エディタ拡張(PropertyAttributeによるstringの文字制限)





PropertyAttributeとは

Unityでは[SerializeField]publicをつけることで変数をinspector上に表示できるが、表示する変数に対して制限を加えたりすることができる。
例えば、次のようにすると、aは「0~50の間の数値をスライダーによって指定する」という機能を加えることができる。

[SerializeField, Range(0, 50)] int a;


これらについてはUnityですでに用意されているものもあるが、PropertyAttributeを使用することで自作することもできる。




今回作成するAttribute

文字列をInspector上で入力するときに、その文字数の上限を設定するもの


StringLengthAttributeクラス

using UnityEngine;

public class StringLengthAttribute : PropertyAttribute
{
    public ushort maxLength;

    public StringLengthAttribute(ushort maxLength)
    {
        this.maxLength = maxLength;
    }
}



StringLengthDrawerクラス

using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(StringLengthAttribute))]
public class StringLengthDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty pr, GUIContent label)
    {
        pr.stringValue = EditorGUI.TextField(position, label, pr.stringValue);

        var max = ((StringLengthAttribute)attribute).maxLength;
        if (pr.stringValue.Length > max)
        {
            pr.stringValue = pr.stringValue.Substring(0, max);
        }
    }
}





使用例

次のように記述することで入力する文字列の5文字以下に制限することができる。

[SerializeField] [StringLength(5)] string a;