-
-
Save aarthificial/f2dbb58e4dbafd0a93713a380b9612af to your computer and use it in GitHub Desktop.
This file contains 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 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
Hi, I did make a custom editor for this Optional which also support passing attributes down to the "T value".
Just want to share this to the community.
Oh, you also need to have Odin Inspector packet
Here are some examples.
OptionalAttributeProcessor.cs
OptionalDrawer.cs