-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReadOnlyAttribute.cs
More file actions
65 lines (56 loc) · 2.34 KB
/
ReadOnlyAttribute.cs
File metadata and controls
65 lines (56 loc) · 2.34 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
using System;
using System.Diagnostics;
using System.Linq;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Jackey.Utilities.Attributes {
/// <summary>
/// Prevents editing this field in the inspector in the specified environment
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
[Conditional("UNITY_EDITOR")]
public sealed class ReadOnlyAttribute : PropertyAttribute {
public Environment Env { get; }
public ReadOnlyAttribute(Environment environment = Environment.Always) {
Env = environment;
}
public enum Environment {
Always,
PlayMode,
EditMode,
PlayModeAndEnabled,
EditModeAndEnabled,
}
}
#if UNITY_EDITOR
namespace PropertyDrawers {
[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
public class ReadOnlyPropertyDrawer : PropertyDrawer {
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
return EditorGUI.GetPropertyHeight(property, label);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
bool condition = ((ReadOnlyAttribute)attribute).Env switch {
ReadOnlyAttribute.Environment.Always => true,
ReadOnlyAttribute.Environment.PlayMode => EditorApplication.isPlaying,
ReadOnlyAttribute.Environment.EditMode => !EditorApplication.isPlaying,
ReadOnlyAttribute.Environment.PlayModeAndEnabled => EditorApplication.isPlaying &&
(property.serializedObject.targetObject is not MonoBehaviour ||
property.serializedObject.targetObjects.All(@object => ((MonoBehaviour)@object).isActiveAndEnabled)),
ReadOnlyAttribute.Environment.EditModeAndEnabled => !EditorApplication.isPlaying &&
(property.serializedObject.targetObject is not MonoBehaviour ||
property.serializedObject.targetObjects.All(@object => ((MonoBehaviour)@object).isActiveAndEnabled)),
_ => throw new ArgumentOutOfRangeException(),
};
label = EditorGUI.BeginProperty(position, label, property);
EditorGUI.BeginDisabledGroup(condition);
EditorGUI.PropertyField(position, property, label, true);
EditorGUI.EndDisabledGroup();
EditorGUI.EndProperty();
}
}
}
#endif
}