-
-
Save artemdemo/42d05eb0dba04608632b0799b4277600 to your computer and use it in GitHub Desktop.
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; | |
| [Serializable] | |
| /// Requires Unity 2020.1+ | |
| public struct Optional<T> | |
| { | |
| [SerializeField] private bool enabled; | |
| [SerializeField] private T value; | |
| public bool Enabled => enabled; | |
| public T Value => value; | |
| public Optional(T initialValue) | |
| { | |
| enabled = true; | |
| value = initialValue; | |
| } | |
| } |
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; | |
| namespace Editor | |
| { | |
| [CustomPropertyDrawer(typeof(Optional<>))] | |
| public class OptionalPropertyDrawer : PropertyDrawer | |
| { | |
| public override float GetPropertyHeight(SerializedProperty property, GUIContent label) | |
| { | |
| var valueProperty = property.FindPropertyRelative("value"); | |
| return EditorGUI.GetPropertyHeight(valueProperty); | |
| } | |
| public override void OnGUI( | |
| Rect position, | |
| SerializedProperty property, | |
| GUIContent label | |
| ) | |
| { | |
| var valueProperty = property.FindPropertyRelative("value"); | |
| var enabledProperty = property.FindPropertyRelative("enabled"); | |
| EditorGUI.BeginProperty(position, label, property); | |
| position.width -= 24; | |
| EditorGUI.BeginDisabledGroup(!enabledProperty.boolValue); | |
| EditorGUI.PropertyField(position, valueProperty, label, true); | |
| EditorGUI.EndDisabledGroup(); | |
| int indent = EditorGUI.indentLevel; | |
| EditorGUI.indentLevel = 0; | |
| position.x += position.width + 24; | |
| position.width = position.height = EditorGUI.GetPropertyHeight(enabledProperty); | |
| position.x -= position.width; | |
| EditorGUI.PropertyField(position, enabledProperty, GUIContent.none); | |
| EditorGUI.indentLevel = indent; | |
| EditorGUI.EndProperty(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment