-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScriptableObjectWithId.cs
More file actions
55 lines (46 loc) · 1.56 KB
/
Copy pathScriptableObjectWithId.cs
File metadata and controls
55 lines (46 loc) · 1.56 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
public class ScriptableObjectWithId : ScriptableObject
{
public string SerializedGuid = null;
[NonSerialized]
private Guid _cachedGuid = Guid.Empty;
public Guid definitionId => GetDefinitionId();
public void ForceNewGuid()
{
SerializedGuid = Guid.NewGuid().ToString();
#if UNITY_EDITOR
EditorUtility.SetDirty(this);
#endif
}
public Guid GetDefinitionId()
{
if (_cachedGuid == Guid.Empty)
{
try
{
_cachedGuid = Guid.Parse(SerializedGuid);
}
catch (Exception e)
{
Debug.LogError($"Guid {SerializedGuid} for {name} is not ready! " + e);
ForceNewGuid();
}
}
return _cachedGuid;
}
}
public class ScriptableObjectIdAttribute : PropertyAttribute { }
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(ScriptableObjectIdAttribute))]
public class ScriptableObjectIdDrawer : PropertyDrawer {
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
GUI.enabled = false;
if (string.IsNullOrEmpty(property.stringValue)) {
Debug.LogError($"ScriptableObjectIdDrawer - Property Value {property.name} is Empty! Assigning new GUID!");
property.stringValue = Guid.NewGuid().ToString();
AssetDatabase.SaveAssets();
}
EditorGUI.PropertyField(position, property, label, true);
GUI.enabled = true;
}
}
#endif