unity通过方法名调用方法
时间: 2023-09-02 22:13:15 浏览: 313
在Unity中,可以使用以下方法通过方法名调用方法:
1. 使用Invoke()方法:Invoke()方法可以根据方法名和延迟时间调用指定的方法。示例如下:
```
Invoke("MethodName", 1.0f);
```
这将在1秒后调用名为MethodName的方法。
2. 使用Delegate:Delegate是一种委托机制,可以将方法作为参数传入。示例如下:
```
public class MyClass : MonoBehaviour {
public delegate void MyDelegate();
public MyDelegate myDelegate;
void Start () {
myDelegate += MethodName;
myDelegate();
}
void MethodName() {
// 方法体
}
}
```
这将在Start()方法中调用名为MethodName的方法。
3. 使用反射:利用反射可以获取指定方法的MethodInfo对象,并调用该方法。示例如下:
```
using System.Reflection;
public class MyClass : MonoBehaviour {
void Start () {
MethodInfo methodInfo = GetType().GetMethod("MethodName");
methodInfo.Invoke(this, null);
}
void MethodName() {
// 方法体
}
}
```
这将在Start()方法中调用名为MethodName的方法。需要注意的是,反射对性能有一定影响,应该谨慎使用。
阅读全文
相关推荐











