Last active
September 8, 2021 18:56
-
-
Save mminer/32bd8b8ac2c199eb1cd223ec1620975b to your computer and use it in GitHub Desktop.
Unity property attribute to conditionally enable a property in the inspector.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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