-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGetComponentInjection.cs
More file actions
62 lines (56 loc) · 2.25 KB
/
GetComponentInjection.cs
File metadata and controls
62 lines (56 loc) · 2.25 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
using System.Reflection;
using System;
using UnityEngine;
public static class GetComponentInjection
{
public static InjectEvent<GetComponentAttribute, FieldInfo, MonoBehaviour> SingleObjectClassifier;
public static InjectEvent<GetComponentAttribute, FieldInfo, MonoHolder<MonoBehaviour, MonoBehaviour[]>> MultipleObjectClassifier;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void InjectScriptReferences()
{
SingleObjectClassifier += (attr, field, obj) =>
{
switch (attr.ComponentAddress)
{
case GetComponentFrom.Self:
field.SetValue(obj, obj.GetComponent(field.FieldType));
break;
case GetComponentFrom.SceneObject:
field.SetValue(obj, MonoBehaviour.FindObjectOfType(field.FieldType));
break;
}
};
Inject();
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
static void InjectGameObjectReferences()
{
MultipleObjectClassifier += (attr, field, monoHolder) =>
{
if (attr.ComponentAddress != GetComponentFrom.TargetGameObject)
return;
GameObject targetObj = GameObject.Find(attr.TargetName);
field.SetValue(monoHolder.t, targetObj.GetComponent(field.GetValue(monoHolder.t).GetType()));
};
Inject();
}
private static void Inject()
{
MonoBehaviour[] objs = MonoBehaviour.FindObjectsOfType<MonoBehaviour>();
foreach (var obj in objs)
{
Type type = obj.GetType();
FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
GetComponentAttribute attr;
foreach (var field in fields)
{
if (field.IsDefined(typeof(GetComponentAttribute), false))
{
attr = field.GetCustomAttribute<GetComponentAttribute>();
SingleObjectClassifier?.Invoke(attr, field, obj);
MultipleObjectClassifier?.Invoke(attr, field, new MonoHolder<MonoBehaviour, MonoBehaviour[]>(obj, objs));
}
}
}
}
}