What is a callback?

I understand everything in this lesson I think, but this term always confuses me and I don’t know what it refers to specifically. What’s the eli5 definition of it?

A callback is essentially just a function that we pass to something else to be called when something happens. It’s called a ‘callback’ because we give it to something to ‘call back’ on. More specifically, we give an address of a function and whatever is ‘calling back’ will just invoke whatever is at that address.

In this lecture, Sam assigns Health.ResetHealth to the event as the callback. So, whenever the UnityEvent is invoked, it will invoke Health.ResetHealth. But he also assigned ParticleSyatem.Play so it invokes the Play method on the particle system and ResetHealth on the health system.

eli5: We give the event our phone number to call when it’s ready to do so, ie. when the player levels up, gimme a call on this number and let me know so that I may do something appropriate.

Sorry, I’m old. I had to google what eli5 is…

So, if I’m understanding correctly, Health.RestoreHealth and ParticleSystem.Play are both callback functions. It’s every method that is being called “back” by an event? Does it apply to things other than events as well? Like If I just have a method that straight up calls a different method, is that a callback?

Yeah, sure. In the Turn Based Strategy course we pass a function to the action we are currently executing. When it is done executing, it executes this function (the callback) to let us know that it is done executing and we can move on to the next turn.

You can make your own. Let’s say you want to display some text in the UI for 5 seconds and after that do something else. You can have a callback to let you know when the text is done displaying so you can do that ‘something else’

// This wil display a message in the console and then another after 5 seconds
private void Start()
    // Call the 'DisplayTextForFiveSeconds' method, passing 'DoSomethingElse' as the callback
    DisplayTextForFiveSeconds("Test text", DoSomethingElse);

private void DisplayTextForFiveSeconds(string text, System.Action callback)
    // Start a coroutine to display the text and wait for 5 seconds
    StartCoroutine(DisplayTextRoutine(text, 5f, callback);

private IEnumerator DisplayTextRoutine(string text, float time, System.Action callback)
    // Display the text
    Debug.Log($"Displaying text: {text}");
    // Wait for some time
    yield return new WaitForSeconds(time);
    // Invoke the callback if it's not null

private void DoSomethingElse()
    // Do something else
    Debug.Log("Doing something else");

Privacy & Terms