Reputation: 592
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?
Upvotes: 9
Views: 18016
Reputation: 90580
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
Upvotes: 20