dome12b
dome12b

Reputation: 623

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?

Upvotes: 1

Views: 4082

Answers (1)

Chris Sinclair
Chris Sinclair

Reputation: 23218

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"]();

Upvotes: 1

Related Questions