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?
Functions, like any other object, can be passed as an argument to another function.
C++ has two ways to pass a function as a parameter. As you see, you can use either operation() or operation2() to give the same result.
Summary. In Python you can pass function objects in to other functions. Functions can be passed around in Python. In fact there are functions built into Python that expect functions to be given as one or more of their arguments so that they can then call them later.
Passing a function as an argument to the function is quite similar to the passing variable as an argument to the function. so variables can be returned from a function. The below examples describe passing a function as a parameter to another function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With