What is a Callback?

I have been doing some online unity research and I can’t seem to find an official documentation on Callbacks in unity. Google instead showed a Unity page about delegates. Are Callbacks, Delegates, and Actions all the same? I don’t think that they are the same, but if that is true what are their differences?

In theory, they are similar. Same same, but different :slight_smile:

A callback is a general term to say a method is meant to be called back whenever something happens. In C#, Events, Actions, and in Unity, UnityEvents, all allow to create callbacks.

In C#, you have Events. They are in the form of a subscriber signature, called a delegate, and an event :

public delegate void EventHandler();
public event EventHandler OnSuchEvent;

Then you subscribe any method that matches the signature like this :

OnSuchEvent += EventHandlingMethod;
void EventHandlingMethod () {}

and unsubscribe like that :

OnSuchEvent -= EventHandlingMethod;

Then you simply raise the event, checking it’s not null first :

if (OnSuchEvent != null)
    OnSuchEvent ();

This events can carry data. In which case, it looks like this :

public delegate void EventHandler(int param);
public event EventHandler OnSuchEvent;
OnSuchEvent += EventHandlingMethod;
void EventHandlingMethod (int param) {}
if (OnSuchEvent != null)
    OnSuchEvent (12);

Then you have Actions. They are generic and save you the trouble of declaring the delegates and checking their null state.

public Action<int> OnSuchEvent;
OnSuchEvent += EventHandlingMethod;
void EventHandlingMethod (int param) {}
OnSuchEvent.Invoke (12);

Unity also has its own UnityEvents, they are also Generic. They show up in the inspector so that you can subscribe other components’ members/methods to them.
You need to add

using UnityEngine.Events;

Then you can use parameter less events like this :

[SerializeField] UnityEvent myEvent;
myEvent.Invoke ();

and with parameters :

[System.Serializable] public class IntEvent : UnityEvent<int> {}
[SerializeField] IntEvent intEvent;
intEvent.Invoke (12);