forked from SteffanDonal/BeatSaber-CustomColors
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathReflectionUtil.cs
60 lines (53 loc) · 2.12 KB
/
ReflectionUtil.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
namespace CustomColors
{
internal static class ReflectionUtil
{
public static void SetPrivateField(this object obj, string fieldName, object value)
{
var field = obj.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
field.SetValue(obj, value);
}
public static T GetPrivateField<T>(this object obj, string fieldName)
{
var field = obj.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
var value = field.GetValue(obj);
return (T)value;
}
public static object GetPrivateField(Type type, object obj, string fieldName)
{
var field = obj.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
var value = field.GetValue(obj);
return value;
}
public static void InvokePrivateMethod(this object obj, string methodName, object[] methodParams)
{
var method = obj.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
method.Invoke(obj, methodParams);
}
public static Component CopyComponent(Component original, Type originalType, Type overridingType, GameObject destination)
{
var copy = destination.AddComponent(overridingType);
Type type = originalType;
while (type != typeof(MonoBehaviour))
{
CopyForType(type, original, copy);
type = type.BaseType;
}
return copy;
}
private static void CopyForType(Type type, Component source, Component destination)
{
FieldInfo[] myObjectFields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField);
foreach (FieldInfo fi in myObjectFields)
{
fi.SetValue(destination, fi.GetValue(source));
}
}
}
}