Skip to content

Instantly share code, notes, and snippets.

@artemdemo
Forked from aarthificial/Optional.cs
Created September 10, 2022 08:29
Show Gist options
  • Select an option

  • Save artemdemo/42d05eb0dba04608632b0799b4277600 to your computer and use it in GitHub Desktop.

Select an option

Save artemdemo/42d05eb0dba04608632b0799b4277600 to your computer and use it in GitHub Desktop.
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;
}
}
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