7

Unity C# doesn't seem to recognize the Func<> symbol as a function delegate. So, how can I pass a function as a function parameter?

I have an idea that Invoke(functionName, 0) might help. But I am not sure whether it actually invokes the function instantly, or waits for the end of the frame. Is there another way?

derHugo
  • 83,094
  • 9
  • 75
  • 115
Coatl
  • 542
  • 3
  • 6
  • 19

1 Answers1

16

You can use Action to do that

using System;

// ...

public void DoSomething(Action callback)
{
    // do something

    callback?.Invoke();
}

and either pass in a method call like

private void DoSomethingWhenDone()
{
    // do something
}

// ...

DoSomething(DoSomethingWhenDone);

or using a lambda

DoSomething(() =>
    {
        // do seomthing when done
    }
);

you can also add parameters e.g.

public void DoSomething(Action<int, string> callback)
{
    // dosomething

    callback?.Invoke(1, "example");
}

and again pass in a method like

private void OnDone(int intValue, string stringValue)
{
    // do something with intVaue and stringValue
}

// ...    

DoSomething(OnDone);

or a lambda

DoSomething((intValue, stringValue) =>
    {
        // do something with intVaue and stringValue
    }
);

Alternatively also see Delegates

and especially for delegates with dynamic parameter count and types check out this post

derHugo
  • 83,094
  • 9
  • 75
  • 115
  • I tried the `Action` solution, but, oddly, Unity doesn't recognize this type either. However, `UnityAction` (using UnityEngine.Events) did the job. So please either tell me how to make `Action` recognizable by the compiler, or edit the `Action` into `UnityAction` so that I can mark your answer as the best one. – Coatl Feb 19 '19 at 18:43
  • no I mean `Action` as it is (you probably can use UnityAction the same way) but just make sure to have `using System;` on top of the script or use `System.Action` – derHugo Feb 19 '19 at 18:47
  • @Coatl Glad to help ;) – derHugo Feb 19 '19 at 18:51
  • Btw, the use of Invoke can be removed. The compiler will add it at compilation but if you want to save that extra typing. So instead of callback.Invoke(); just callback(); same same not different. – Everts Feb 19 '19 at 21:07
  • @Everts yes or use `callback?.Invoke()` for having an additional null-check (from c# 6) ... I think it's a mater of preference (see [here](https://stackoverflow.com/q/9259470/7111561)) .. I prefer to make clear that it's an `Action` not a usual method I'm calling ;) – derHugo Feb 19 '19 at 21:11