【Unity】Publicな変数を編集できないようにするCustom Attributeを作成する

はじめに

Publicな変数を編集できないようにするReadOnlyなCustom Attributeを作成します

スクリプト

using UnityEngine;
using UnityEditor;

public class ReadOnlyAttribute : PropertyAttribute { }


[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
public class ReadOnlyDrawer : PropertyDrawer
{

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        GUI.enabled = false;
        EditorGUI.PropertyField(position, property, label, true);
    }
}

使い方

using UnityEngine;

public class Test : MonoBehaviour
{
    [ReadOnly]
    public float test;
}

下記のように編集できないようになります