0
\$\begingroup\$

I want to store functions with parameters in a List, so that I can call them at a later stage.

Let's say (this is rough code)

void Func1(int index)
{
   Debug.Log("Func1"+index)
}

void Func2(int index)
{
   Debug.Log("Func2"+index)
}
.
.
.

void Store(Func1(1))
{
  list.Add(Func1(1));
}

void Replay(int position)
{
  list[position](); // this calls the function with the parameter
}
\$\endgroup\$
  • 1
    \$\begingroup\$ use a lambda expression: Action f = () => Func1 (1); f (); \$\endgroup\$ – trollingchar Dec 5 '19 at 6:55
  • \$\begingroup\$ @trollingchar Sorry I quite not understand by what you mean. Can you please elaborate. Thanks \$\endgroup\$ – Hash Buoy Dec 5 '19 at 7:22
6
\$\begingroup\$

You declare that you have a list of actions:

List<Action> list;

Do not forget to initialize it:

list = new List<Action>();

Then, you create an action from the function using a lambda expression:

Action action = () => Func1(1);

And you add the action to the list:

list.Add(action);

You can, of course, inline the lambda expression:

list.Add(() => Func1(1));

Afterwards you can call the actions, for example, in a loop:

foreach (var action in list)
{
    action.Invoke();
}

Actually, you do not need to use Invoke:

foreach (var action in list)
{
    action();
}

Ah, yes, that works too:

list[position]();
\$\endgroup\$
  • \$\begingroup\$ Thanks a lot for a detailed answer, will try it and let you know :) \$\endgroup\$ – Hash Buoy Dec 5 '19 at 7:34
  • \$\begingroup\$ Works fine, thanks a lot !!! \$\endgroup\$ – Hash Buoy Dec 5 '19 at 12:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.