unity使用枚举实现不同参方法管理,动态添加移除方法监听时将枚举和方法组绑定,调用时传枚举和参数调用相应方法
时间: 2024-03-16 09:42:06 浏览: 15
在 Unity 中,可以使用字典将枚举和方法组绑定,实现动态添加、移除方法监听,并且可以通过枚举和参数调用相应的方法。以下是示例代码:
定义委托:
```
public delegate void MyMethodDelegate(int arg1, float arg2);
```
定义字典:
```
private Dictionary<MyMethodType, MyMethodDelegate> methodDict = new Dictionary<MyMethodType, MyMethodDelegate>();
```
定义枚举类型:
```
public enum MyMethodType
{
Method1,
Method2,
Method3
}
```
动态添加方法监听:
```
methodDict.Add(MyMethodType.Method1, Method1);
methodDict.Add(MyMethodType.Method2, Method2);
methodDict.Add(MyMethodType.Method3, Method3);
```
动态移除方法监听:
```
methodDict.Remove(MyMethodType.Method1);
methodDict.Remove(MyMethodType.Method2);
methodDict.Remove(MyMethodType.Method3);
```
实现不同的方法:
```
private void Method1(int arg1, float arg2)
{
// 处理 Method1 的逻辑,使用 arg1 和 arg2。
}
private void Method2(int arg1, float arg2)
{
// 处理 Method2 的逻辑,使用 arg1 和 arg2。
}
private void Method3(int arg1, float arg2)
{
// 处理 Method3 的逻辑,使用 arg1 和 arg2。
}
```
调用方法:
```
public void InvokeMethod(MyMethodType methodType, int arg1, float arg2)
{
if (methodDict.ContainsKey(methodType))
{
methodDict[methodType]?.Invoke(arg1, arg2);
}
}
```
在调用方法时,可以指定不同的枚举值并传入对应的参数,方法内部使用字典和委托动态调用不同的方法。可以通过动态添加、移除方法监听,实现方法的灵活管理。