dictionary and pointers

As a beginner with unity and c#, hoping someone can give me some “pointers” (pardon the pun)… :slight_smile: I’m trying to set up a dictionary of “pointers” to a series of functions.
So I have something like this:
Dictionary<string,Action> testpointers = new Dictionary<string, Action>()
{
{“test1”, () => Routine_1() },
{“test2”, () => Routine_2() }
};

void Routine_1{}
void Routine_2{}

I want to use the values, the pointers, in things like AddListener etc so I can change things dynamically using my dictionary. How do I get the function/method “label” as an “pointer”. If I do something like this
var showme = testpointers[“test1”] all I get in debug.log is “System.Action”.

Thanks

You can do this but the syntax to “get a pointer” to a function omits the ()

You don’t need to re-wrap it in a delegate, but you’re welcome to.

The () after the function is the “invoke this function”

To invoke showme, you would do:

showme();

or if you like living dangerously:

testpointers["test1"]();

I always advocate pulling it out and testing it for nullness however.

Dictionary<string,System.Action> testpointers =
    new Dictionary<string, System.Action>()
{
    {"test1", Routine_1 },
    {"test2", Routine_2 }
};

static void Routine_1() { print("one"); }
static void Routine_2() { print("two"); }

Edit: or if you need to pass an argument:

Dictionary<string,System.Action<object>> testpointers =
    new Dictionary<string, System.Action<object>>()
{
    {"test1", Routine_1 },
    {"test2", Routine_2 }
};
static void Routine_1(object o) { print($"one {o}"); }
static void Routine_2(object o) { print($"two {o}"); }

Thanks you both for this. Still having a bit of a fix though.
I’m doing this:

  • Dictionary<string,System.Action> testpointers =
  • new Dictionary<string, System.Action>()
  • {
  • {“test1”, Routine_1 },
  • {“test2”, Routine_2 }
  • };

as in the example above.
Then I try to use the “pointer”/value in the way I would in Python or whatever by simply grabbing it with the key and dumping it in.

But …AddListener(testpointers[“test1”]) doesn’t work. I get "cannot convert from system.action to unityengine.events.unityaction. What I’m trying to do is set up an array of delegates (I think that’s what c# calls them, as Kurt in post above points out; I just call them pointers) that I can pick out and use (as in example with AddListener) by using the keys as references.

I must be missing a step somewhere.

Oh yeah, you just gotta wrap it with delegate…

Syntax would look like:

AddListener( delegate { testpointers["test1"](); } );

But again, if you think the retrieve might fail, obviously hook up a try/catch or a .ContainsKey() check.

Thank you so much. You’re a star. This is finally working and now I can get on. :slight_smile: Thank you.

@halley1

Thanks for helping me resolve this as well.