Search code examples
c#delegatesaction

Action parameter with possible multiple args


I have a WaitAndRun function. I want this method to be very generic.

public static IEnumerator WaitAndRun<T>(float time, Action<T> action, object arg)
{
    yield return new WaitForSeconds(time);
    action((T)arg);
}

It works perfectly with the following example:

void an_action(int x)
{
    Debug.Log(x);
}
//...
WaitAndRun<int>(1, an_action, 2);

The problem is I want to use the same definition when I need multiple args as well. How can I make this function support calling single and multiple args at the same time? For instance:

void another_action(int x, int y);

If I useobject[] args instead of object arg, I am not sure about how to modify the remaining part.

Edit: changed func to action


Solution

  • Here's an alternative suggestion: Use lambda expressions and their ability to capture local variables:

    public static IEnumerator WaitAndRun(float time, Action action)
    {
        yield return new WaitForSeconds(time);
        action();
    }
    

    Usage:

    WaitAndRun(1, () => an_action(2));
    WaitAndRun(1, () => another_action(2, 3));