Skip to content

Instantly share code, notes, and snippets.

@mminer
Last active September 8, 2021 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mminer/32bd8b8ac2c199eb1cd223ec1620975b to your computer and use it in GitHub Desktop.
Save mminer/32bd8b8ac2c199eb1cd223ec1620975b to your computer and use it in GitHub Desktop.
Unity property attribute to conditionally enable a property in the inspector.
using System;
using UnityEngine;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Struct)]
public class ConditionalEnableAttribute : PropertyAttribute
{
public readonly string ConditionalPropertyName;
public ConditionalEnableAttribute(string conditionalPropertyName)
{
ConditionalPropertyName = conditionalPropertyName;
}
}
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(ConditionalEnableAttribute))]
public class ConditionalEnablePropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var conditionalDisableAttribute = (ConditionalEnableAttribute)attribute;
var isEnabled = IsEnabled(conditionalDisableAttribute, property);
using (new EditorGUI.DisabledScope(!isEnabled))
{
EditorGUI.PropertyField(position, property, label, true);
}
}
static bool IsEnabled(ConditionalEnableAttribute conditionalEnableAttribute, SerializedProperty property)
{
var conditionalPropertyPath = property.propertyPath.Replace(property.name, conditionalEnableAttribute.ConditionalPropertyName);
var conditionalProperty = property.serializedObject.FindProperty(conditionalPropertyPath);
if (conditionalProperty == null)
{
Debug.LogWarning($"No conditional property found for ConditionalEnableAttribute: {conditionalEnableAttribute.ConditionalPropertyName}");
return true;
}
return conditionalProperty.boolValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment