0

Hi Folks i am trying to learn more about the Action Delegates in C# but i dont understand it so good. So below i have a Code Example from a Unity C# Project. My Question is. What is the purpose of this "Action doneCallback" parameter and what does do the "doneCallback.Invoke()" code exactly. Thanks in Advance!

public static IEnumerator StartWaiting(
    float time, Action doneCallback, 
    float increment, Action<float> incrementCallback, 
    bool countUp = true)
{
    float timeElapsed = 0f;
    float timeRemaining = time;

    while (timeRemaining > 0f)
    {
        yield return new WaitForSeconds(increment);
        timeRemaining -= increment;
        timeElapsed += increment;
        incrementCallback.Invoke(countUp ? timeElapsed : timeRemaining);
    }
    doneCallback.Invoke();
}

public static IEnumerator StartWaiting(float time, 
    Action doneCallback)
{
    yield return new WaitForSeconds(time);
    doneCallback.Invoke();
}

}

Hakki Uzel
  • 39
  • 6
  • 1
    You can see them as a "pointer" to a method. Invoke executes that method. http://dotnetpattern.com/csharp-action-delegate So basically in your code you can pass any method that has a float parameter (e.g. `private void CoolMethod(float bla)`) to the incremenentCallback parameter. – Legacy Code Jul 23 '20 at 15:10

1 Answers1

0

This is the definition of Action:

public delegate void Action();

It is a placeholder for a function that returns void and accepts no arguments.

You could use any method or anonymous function / lambda expression that matches its signature.

As an example:

StartWaiting(1000f, () => Console.WriteLine("done"));

Or another:

private void WriteToConsole()
{
    Console.WriteLine("done");
}

StartWaiting(1000f, WriteToConsole);

doneCallback.Invoke(); actually invokes that function, but you could also write this as doneCallback(); they are equivalent.


Similarly, this is Action<T>:

public delegate void Action<in T>(T obj);

So Action<float> is a placeholder for a function that returns void and accepts a single argument of type float.

An example:

var increments = new List<float>();
StartWaiting(1000f, WriteToConsole, 1f, floats.Add);
Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35