Search code examples
c#unity-game-engine

How to display a private field in the Unity Inspector as read-only


I’m working on a Unity project and I have a private field in one of my scripts that I’d like to display in the Unity Inspector. However, I want to ensure that this field is read-only and cannot be modified from the Inspector, just like private fields appear in Debug mode?

Below is a picture showing a private field in Debug mode. enter image description here

It can be a package, a custom editor, or anything else.


Solution

  • One way to solve it is creating a custom PropertyAttributes/Drawer, like this one:

    PropertyAttribute:

    using UnityEngine;
    
    public class DisplayWithoutEdit : PropertyAttribute
    {
    }
    

    PropertyDrawer:

    using UnityEditor;
    using UnityEngine;
    
    [CustomPropertyDrawer(typeof(DisplayWithoutEdit))]
    public class DisplayWithoutEditDrawer : 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;
        }
    }
    

    Use it like:

    [SerializeField, DisplayWithoutEdit] private int variable = 2;