将函数存储在Unity3D中的List或Array中

本文关键字:List Array 中的 Unity3D 函数 存储 | 更新日期: 2023-09-27 18:19:31

我试图在不使用太多if语句(C#)的情况下加载不同的函数。我尝试过使用Lists,但对Unity使用Action抛出了一个异常。我在这里找到了一个很好的c#解决方案:

var methods = new Dictionary<string, Action>()
          {
              {"method1", () => method1() },
              {"method2", () => method2() }
          };
methods["method2"]();

Action 也存在同样的问题

我进口

using System.Collections.Generic;

我想念什么?

将函数存储在Unity3D中的List或Array中

除了为Dictionary导入System.Collections.Generic外,还需要为Action导入System

using System;添加到文件顶部。

通常,在MSDN上查找该类型可以查看其完整的命名空间。在这种情况下,Action委托的MSDN页面指示其命名空间为"System"。因此,您必须在代码顶部添加using System;指令,或者在代码中包含完整的命名空间。例如,如果您有,您可以在没有using指令的情况下重写上面的代码

var methods = new System.Collections.Generic.Dictionary<string, System.Action>()
      {
          {"method1", () => method1() },
          {"method2", () => method2() }
      };
methods["method2"]();
相关文章: