EnabledIfAttribute.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using UnityEngine;
  3. #if UNITY_EDITOR
  4. using UnityEditor;
  5. #endif
  6. namespace UnityUIPlayables
  7. {
  8. [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
  9. internal class EnabledIfAttribute : MultiPropertyAttribute
  10. {
  11. public enum HideMode
  12. {
  13. Invisible,
  14. Disabled
  15. }
  16. private readonly int _enableIfValueIs;
  17. private readonly HideMode _hideMode;
  18. private readonly string _switcherFieldName;
  19. public EnabledIfAttribute(string switcherFieldName, bool enableIfValueIs, HideMode hideMode = HideMode.Disabled)
  20. : this(switcherFieldName, enableIfValueIs ? 1 : 0, hideMode)
  21. {
  22. }
  23. public EnabledIfAttribute(string switcherFieldName, int enableIfValueIs, HideMode hideMode = HideMode.Disabled)
  24. {
  25. _hideMode = hideMode;
  26. _switcherFieldName = switcherFieldName;
  27. _enableIfValueIs = enableIfValueIs;
  28. }
  29. #if UNITY_EDITOR
  30. public override void OnPreGUI(Rect position, SerializedProperty property)
  31. {
  32. var isEnabled = GetIsEnabled(property);
  33. if (_hideMode == HideMode.Disabled)
  34. {
  35. GUI.enabled &= isEnabled;
  36. }
  37. }
  38. public override void OnPostGUI(Rect position, SerializedProperty property, bool changed)
  39. {
  40. if (_hideMode == HideMode.Disabled)
  41. {
  42. GUI.enabled = true;
  43. }
  44. }
  45. public override bool IsVisible(SerializedProperty property)
  46. {
  47. return _hideMode != HideMode.Invisible || GetIsEnabled(property);
  48. }
  49. private bool GetIsEnabled(SerializedProperty property)
  50. {
  51. return _enableIfValueIs == GetSwitcherPropertyValue(property);
  52. }
  53. private int GetSwitcherPropertyValue(SerializedProperty property)
  54. {
  55. var propertyNameIndex = property.propertyPath.LastIndexOf(property.name, StringComparison.Ordinal);
  56. var switcherPropertyName = property.propertyPath.Substring(0, propertyNameIndex) + _switcherFieldName;
  57. var switcherProperty = property.serializedObject.FindProperty(switcherPropertyName);
  58. switch (switcherProperty.propertyType)
  59. {
  60. case SerializedPropertyType.Boolean:
  61. return switcherProperty.boolValue ? 1 : 0;
  62. case SerializedPropertyType.Enum:
  63. return switcherProperty.intValue;
  64. default:
  65. throw new Exception("unsupported type.");
  66. }
  67. }
  68. #endif
  69. }
  70. }