-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnity_Invoke-Method-by-Stringname
More file actions
69 lines (45 loc) · 1.71 KB
/
Unity_Invoke-Method-by-Stringname
File metadata and controls
69 lines (45 loc) · 1.71 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
using System.Reflection;
public class SCRIPNAME : MonoBehaviour
{
private void Start()
{
var function = typeof("TYPENAME").GetMethod("METHODNAME", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
function.Invoke(this, null);
}
//EXAMPLE 1
public void ItemCollected()
{ //this.name matches the name of the script, so the function with the same name will be called
var function = typeof(Collectable).GetMethod(this.name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
function.Invoke(this, null);
}
//method with the same name as the script to be called. within the context of the example could be the name of an item
private void SCRIPNAME()
{
Debug.Log("EXAMPLE1");
}
//EXAMPLE 2
//BindingFlags are needed to call private functions only
public void EXAMPLE2()
{ //this.name matches the name of the script, so the function with the same name will be called
var function = typeof(Collectable).GetMethod(METHODNAME);
function.Invoke(this, null);
}
//necessarily public method to be called
public void METHODNAME()
{
Debug.Log("EXAMPLE2");
}
//EXAMPLE 3
//again using BindingFlags, but storing type in a flag
void Start()
{
//returns the type of this component
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod("bla", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
theMethod.Invoke(this, null);
}
private void METHODNAME()
{
Debug.Log("EXAMPLE3");
}
}