简体   繁体   中英

Passing a function as a function parameter

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?

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 eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM