-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConditionalPropertyAttributes.cs
More file actions
250 lines (211 loc) · 8.85 KB
/
ConditionalPropertyAttributes.cs
File metadata and controls
250 lines (211 loc) · 8.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
// Description: Unity 'EnableIf' and 'ShowIf' property attributes.
//
// Updated: 2020-05-16
/* MIT License
*
* Copyright (c) 2021 Jonatan Johansson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
public abstract class ConditionalPropertyAttribute : PropertyAttribute {
/// <summary>The name of the field to use.</summary>
public string Reference { get; }
/// <summary>The value to compare against.</summary>
public object Comparand { get; }
/// <summary>Invert the condition.</summary>
public bool Invert { get; set; }
internal bool IsComparison { get; }
public ConditionalPropertyAttribute(string reference) {
Reference = reference;
}
public ConditionalPropertyAttribute(string reference, object comparand) {
Reference = reference;
Comparand = comparand;
IsComparison = true;
}
}
/// <summary>
/// Disables a serialized field in the inspector if a certain condition evaluates to false. The condition can be
/// inverted with <see cref="ConditionalPropertyAttribute.Invert"/>.
/// </summary>
public class EnableIfAttribute : ConditionalPropertyAttribute {
/// <summary>
/// Disable the serialized field in the inspector unless the field with the name specified by <paramref name="reference"/>
/// contains a truthy value.
/// </summary>
/// <param name="reference">The name of the reference field.</param>
/// <remarks>
/// <para>A value is considered truthy if it is neither null nor 0.</para>
/// <para>The referenced field must be accessible from within the type in which the attribute is used.</para>
/// </remarks>
public EnableIfAttribute(string reference) : base(reference) { }
/// <summary>
/// Disable the serialized field in the inspector unless the value contained in the reference field is equal to
/// <paramref name="comparand"/>.
/// </summary>
/// <param name="reference">The name of the reference field.</param>
/// <param name="comparand">The value to compare against.</param>
/// <remarks>
/// <para>The referenced field must be accessible from within the type in which the attribute is used.</para>
/// </remarks>
public EnableIfAttribute(string reference, object comparand) : base(reference, comparand) { }
}
/// <summary>
/// Hide a serialized field in the inspector if a certain condition evaluates to false. The condition can be
/// inverted with <see cref="ConditionalPropertyAttribute.Invert"/>.
/// </summary>
public class ShowIfAttribute : ConditionalPropertyAttribute {
/// <summary>
/// Hide the serialized field in the inspector unless the field with the name specified by <paramref name="reference"/>
/// contains a truthy value.
/// </summary>
/// <param name="reference">The name of the reference field.</param>
/// <remarks>
/// <para>A value is considered truthy if it is neither null nor 0.</para>
/// <para>The referenced field must be accessible from within the type in which the attribute is used.</para>
/// </remarks>
public ShowIfAttribute(string reference) : base(reference) { }
/// <summary>
/// Hide the serialized field in the inspector unless the value contained in the reference field is equal to
/// <paramref name="comparand" />.
/// </summary>
/// <param name="reference">The name of the reference field.</param>
/// <param name="comparand">The value to compare against.</param>
/// <remarks>
/// <para>The referenced field must be accessible from within the type in which the attribute is used.</para>
/// </remarks>
public ShowIfAttribute(string reference, object comparand) : base(reference, comparand) { }
}
#if UNITY_EDITOR
namespace PropertyDrawers {
[CustomPropertyDrawer(typeof(ConditionalPropertyAttribute), true)]
public class ConditionalPropertyDrawer : PropertyDrawer {
private const int HelpBoxPadding = 2;
private const int HelpBoxMinHeight = 38; // Magic constant.
private Type cachedReferenceFieldType;
private FieldInfo cachedReferenceField;
private bool cachedReferenceFieldStatic;
private bool ok;
private bool needsUpdate;
private bool conditionResult;
private string errorMessage;
private float propHeight;
public override bool CanCacheInspectorGUI(SerializedProperty property) {
return false; // Probably not?
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
EvaluateCondition(property);
if (ok && attribute is ShowIfAttribute && !conditionResult)
return 0f; // Hidden.
float height = propHeight = EditorGUI.GetPropertyHeight(property, label, true);
if (!ok && errorMessage != null)
height += HelpBoxPadding + Mathf.Max(HelpBoxMinHeight,
EditorStyles.helpBox.CalcHeight(
new GUIContent(errorMessage),
EditorGUIUtility.currentViewWidth));
return height;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
if (needsUpdate) {
Debug.Assert(false, "GetPropertyHeight did not execute before OnGUI.");
EvaluateCondition(property);
}
needsUpdate = true;
if (ok) {
if (attribute is EnableIfAttribute) {
EditorGUI.BeginDisabledGroup(!conditionResult);
EditorGUI.PropertyField(position, property, label, true);
EditorGUI.EndDisabledGroup();
return;
}
if (attribute is ShowIfAttribute && !conditionResult)
return; // Hidden.
}
else {
if (errorMessage != null) {
EditorGUI.PropertyField(position, property, label, true);
position.yMin += HelpBoxPadding + propHeight;
EditorGUI.HelpBox(position, errorMessage, MessageType.Error);
return;
}
}
// Fallback to default drawer.
EditorGUI.PropertyField(position, property, label, true);
}
private void EvaluateCondition(SerializedProperty property) {
ConditionalPropertyAttribute attr = attribute as ConditionalPropertyAttribute;
ok = false;
errorMessage = null;
needsUpdate = false;
// Validate
if (attr == null) return;
if (attr.Reference == null) {
errorMessage = "Field reference is null.";
return;
}
SerializedObject serializedObject = property.serializedObject;
// Show default when multi editing objects.
if (serializedObject.isEditingMultipleObjects) return;
Object target = serializedObject.targetObject;
if (target == null) return;
// Find the reference field
Type declType = fieldInfo.DeclaringType;
Debug.Assert(declType != null);
if (cachedReferenceField == null) {
cachedReferenceField = declType.GetField(attr.Reference,
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static);
if (cachedReferenceField == null) {
errorMessage = $"No field named '{attr.Reference}' found in type '{declType.Name}'.";
return;
}
cachedReferenceFieldType = cachedReferenceField.FieldType;
cachedReferenceFieldStatic = cachedReferenceField.IsStatic;
}
// Check the condition
object value = cachedReferenceField.GetValue(cachedReferenceFieldStatic ? null : target);
bool result = attr.IsComparison
? Equals(value, attr.Comparand)
: IsTruthy(value, cachedReferenceFieldType);
// Store the result
conditionResult = attr.Invert ? !result : result;
ok = true;
}
/// <summary>
/// Check if a value is considered truthy.
/// </summary>
private static bool IsTruthy(object value, Type type) {
if (type.IsValueType && value is IConvertible convertible) {
TypeCode typeCode = convertible.GetTypeCode();
if (typeCode == TypeCode.Object || typeCode == TypeCode.DateTime)
return true;
// All numbers are convertible to double
try { return convertible.ToDouble(null) != 0.0; }
catch { /* ignored */ }
}
return value != null && !value.Equals(null);
}
}
}
#endif