Skip to content

Instantly share code, notes, and snippets.

@mstevenson
Created November 8, 2019 05:33
Show Gist options
  • Save mstevenson/f731079e338c0aa535b1c80ab9cf2d6b to your computer and use it in GitHub Desktop.
Save mstevenson/f731079e338c0aa535b1c80ab9cf2d6b to your computer and use it in GitHub Desktop.
Visually indicate that a Unity inspector value is required.
using System;
using UnityEngine;
/// <summary>
/// Indicates that an inspector field must have its value assigned during authoring.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class RequiredFieldAttribute : PropertyAttribute
{
}
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(RequiredFieldAttribute))]
public class RequiredFieldPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
SerializedProperty prop = property.serializedObject.FindProperty(property.propertyPath);
bool isNotNull = CheckNotNull(prop);
if (!isNotNull)
{
var color = GUI.color;
var lineRect = new Rect(position)
{
xMax = position.xMin,
xMin = position.xMin - 3,
yMin = position.yMin + 1,
yMax = position.yMax - 1
};
EditorGUI.DrawRect(lineRect, new Color(0.75f, 0f, 0f));
GUI.color = color;
}
EditorGUI.PropertyField(position, property, label, true);
}
private static bool CheckNotNull(SerializedProperty property)
{
switch (property.propertyType)
{
case SerializedPropertyType.String:
return !string.IsNullOrEmpty(property.stringValue);
case SerializedPropertyType.ObjectReference:
return property.objectReferenceValue != null;
case SerializedPropertyType.AnimationCurve:
return property.animationCurveValue.keys.Length > 0;
case SerializedPropertyType.ExposedReference:
return property.exposedReferenceValue != null;
default:
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment