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.
>Solution :
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.