1

I'm trying to pass a function as an argument just like this:

void AvoidSpawn(float sRate, function f) 
    {
        float calculateRate = 0;
        if(Time.time>=calculateRate)
        {
            f();
            calculateRate = Time.time + spawnRate;
        }
    }

I don't know how to use a function as an argument and pass it and I would like to replace function f with something that works.

Tien Hung
  • 139
  • 8
  • 1
    Read about [delegates](https://learn.microsoft.com/en-US/dotnet/csharp/programming-guide/delegates/). Then read about [Action](https://learn.microsoft.com/en-us/dotnet/api/system.action?view=net-7.0) and [Func](https://learn.microsoft.com/en-us/dotnet/api/system.func-1?view=net-7.0) – Zohar Peled Nov 22 '22 at 10:05
  • 1
    Or read https://learn.microsoft.com/en-us/dotnet/api/system.func-2?view=net-7.0 – swatsonpicken Nov 22 '22 at 10:06
  • 1
    Duplicate of: [this](https://stackoverflow.com/q/3622160/13927459) and [this](https://stackoverflow.com/q/2082615/13927459) ? – JohnFrum Nov 22 '22 at 10:06

1 Answers1

2

For a function that doesn't return any value (a void method), there are various Action delegates.

For a function that does return a value, you need Func and friends.

There are various versions to account for a number of parameters (up to 16, nowadays).

So you can define your function as

void AvoidSpawn(float sRate, Action f) 
{
   // ...
   f();
   // ...
}

And either call it with a lambda:

AvoidSpawn(1.0f, () => Console.WriteLine("Avoiding spawn"));

or mention another method

AvoidSpawn(1.0f, SomeVoidMethod);

Note: do not use () there, you don't want to call that method yet.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111