Search code examples
c#unity-game-engineunity-editor

Unity EditorGUI.PropertyField can't fully disable array or List


So, here is the code:

// ReadOnlyAttribyte,cs
public class ReadOnlyAttribute : PropertyAttribute
{

}

// ReadOnlyDrawer.cs
[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
public class ReadOnlyDrawer : 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;
 }
}

// test
[System.Serializable]
public class GridObjectData : ScriptableObject 
{
    [ReadOnly]
    public int ID;

[ReadOnly]
public List<GridCell> Grid;
}

Here is a simple custom attribute and attribute drawer that allows us to disable all marked(by [ReadOnly]) fields to be disabled in GUI. So the elements of the List are disabled, however the size of the list is still enabled in GUI. How could I fix that ?

Thank you.

Update: Please take a look how it looks in the inspector


Solution

  • The problem is that your Property Drawer is used for rendering each element (property) in the list, and not the list itself as a whole.

    As such. every property does become read only, but the list object itself is still rendered the same, and the way Unity presents it is by showing the "Size" property.