-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoRefAttribute.cs
More file actions
71 lines (58 loc) · 2.29 KB
/
Copy pathAutoRefAttribute.cs
File metadata and controls
71 lines (58 loc) · 2.29 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
using System;
using System.Reflection;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine.UIElements;
#endif
namespace RocketWorks
{
[System.AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
public class AutoRefAttribute : PropertyAttribute
{
public AutoRefAttribute()
{
}
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(AutoRefAttribute))]
public class AutoRefDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.PropertyField(position, property);
if (property.objectReferenceValue != null)
return;
var objType = property.serializedObject.targetObject.GetType();
FieldInfo field = null;
while (field == null && objType.BaseType != null)
{
field = objType.GetField(property.propertyPath, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
objType = objType.BaseType;
}
var propertyType = field.FieldType;
if (propertyType.IsSubclassOf(typeof(Behaviour)))
{
var monoBehaviour = (Behaviour)property.serializedObject.targetObject;
var foundBehaviour = monoBehaviour.GetComponentInChildren(this.fieldInfo.FieldType);
if (property.objectReferenceValue == foundBehaviour)
return;
property.objectReferenceValue = foundBehaviour;
property.serializedObject.ApplyModifiedProperties();
}
if (propertyType.IsSubclassOf(typeof(ScriptableObject)))
{
var filter = $"t:{propertyType.Name}";
var paths = AssetDatabase.FindAssets(filter);
if (paths.Length == 0)
return;
var firstFoundAsset = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(paths[0]), propertyType);
if (property.objectReferenceValue == firstFoundAsset)
return;
property.objectReferenceValue = firstFoundAsset;
property.serializedObject.ApplyModifiedProperties();
}
}
}
#endif
}