編集不可のパラメータをインスペクターに表示したいという機会があり、PropertyAttribute、PropertyDrawerを継承して処理を書くやり方があったので試しにやってみました。
環境
- Unity2018.3.7f1
- MacBookPro Mojave v10.14.3
実装
NonEditableAttribute.csというスクリプトを作成して、PropertyAttributeとPropertyDrawerクラスを継承したクラスを定義しました。(ReadOnlyAttributeという名前にしたかったのですが、Unity側に既にあった為、被らない名前にしました。)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif public sealed class NonEditableAttribute : PropertyAttribute{} #if UNITY_EDITOR [CustomPropertyDrawer( typeof(NonEditableAttribute) )] public sealed class NonEditableAttributeDrawer : PropertyDrawer { public override float GetPropertyHeight ( SerializedProperty property, GUIContent label ) { return EditorGUI.GetPropertyHeight( property, label, true ); } public override void OnGUI ( Rect position, SerializedProperty property, GUIContent label ) { GUI.enabled = false; EditorGUI.PropertyField( position, property, label, true ); GUI.enabled = true; } } #endif |
他サイトでは、PropertyDrawerクラスを継承しているクラスはEditorフォルダ内に入れていましたが、#if UNITY_EDITORで囲う形にするとEditorフォルダにいれなくても使えた為、こういう形にしてみました。
使い方はこちら
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class NonEditableAttributeTest : MonoBehaviour { [SerializeField,NonEditable] private int m_iValue = 10; [SerializeField,NonEditable] private float m_fValue = 0.5f; [SerializeField,NonEditable] private string m_strValue = "NonEditable"; [SerializeField,NonEditable] private List<int> m_iValues = new List<int>() { 1, 2, 3, 4, 5 }; } |
インスペクタ表示はこんな感じに!

ListのSizeは編集できてしまうようで、ここも編集出来ない形にできると良かったのですが・・・。
まとめ
値を確認したいだけの時に、編集不可にして表示するととても便利でした。他にも色々できそうなのでインスペクタ表示についても色々調べていこうと思います。