简体   繁体   中英

Store functions in List or Array in Unity3D

I am trying to load different functions without using to much if statements (C#). I tried using Lists, but to Unity throws an exception by using Action . I found a nice solution for c# here:

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

methods["method2"]();

Same problem here with the Action

I imported

using System.Collections.Generic;

What do I miss?

In addition to System.Collections.Generic for the Dictionary , you also need to import System for the Action .

Add using System; to the top of your file.

In general, look up the type on MSDN to see its full namespace. In this case, the MSDN page for the Action delegate indicates that its namespace is "System". As such, you'll either have to add a using System; directive at the top of your code or include the full namespace in your code. So for example, you could rewrite your code above without using directives if you have:

var methods = new System.Collections.Generic.Dictionary<string, System.Action>()
      {
          {"method1", () => method1() },
          {"method2", () => method2() }
      };

methods["method2"]();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM