Change the color of a variable field if it is empty

I recently saw this post on facebook and i did the same because it would be useful to me, but here it doesn’t work…

His code:


Expeted result:

My code:

#region Libraries
using UnityEditor;
using UnityEngine;

#endregion

[CustomPropertyDrawer(typeof(WarnIfEmpty))]
public class FieldCantBeNull : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        WarnIfEmpty warn = attribute as WarnIfEmpty;
       
        if (property.objectReferenceValue == null)
        {
            GUI.color = warn.color;
            EditorGUI.PropertyField(position, property, label);
            GUI.color = Color.white;
        }
        else
        {
            EditorGUI.PropertyField(position, property, label);
        }
    }
}

public class WarnIfEmpty : PropertyAttribute
{
    public Color color = Color.red;
}

Unexpeted result:

What am I doing wrong?

Before inspecting the code too deeply, put some breakpoints in the OnGUI function, attach the debugger, see if it’s even being called.

1 Like