How do Delegates and Events work?

I’ve looked around and saw few examples and tutorials, each one was explaining differently and I couldn’t understand how exactly do they work.

so:

  • What is Delegate

  • What is Event

  • How to use Delegate

  • How to use Event

I’m posting this Q&A as I saw non other to fit logically how they work at least in my mind.

if you are wandering why OAFAT title? It might be first but I hope it won’t be last.

  • Delegate is a container of events (we could say array)

  • Events are container of pointers to functions (we could say array)

I’ll try to write as many different names as possible so you can see how it works.

using UnityEngine;
using System.Collections;

public class EventManager : MonoBehaviour {
	public delegate void DelegateContainer ();
	public static event DelegateContainer EventContainerOne; // this is when DelegateContainer adds event container to him self
	public static event DelegateContainer EventContainerTwo;

	public bool EditorTriggerOne = false;
	public bool EditorTriggerTwo = false;
	public bool EditorTriggerReset = false;

	void Update(){
		if (EditorTriggerOne){
			TriggerOne();
			EditorTriggerOne = false;
		}
		if (EditorTriggerTwo){
			TriggerTwo();
			EditorTriggerTwo = false;
		}
		if (EditorTriggerReset){
			Reset();
			EditorTriggerReset = false;
		}
	}
	
	// NormalFunctions
	public void TriggerOne(){
		// if there's no pointers to functions in EventContainerOne it'll give us NRE error
		if (EventContainerOne != null){
			// we fire all functions inside this EventContainer
			EventContainerOne();
		}
	}
	public void TriggerTwo(){
		if (EventContainerTwo != null){
			EventContainerTwo();
		}
	}
	// here we remove all functions from events
	public void Reset(){
		EventContainerOne = null;
		EventContainerTwo = null;
	}
}

Random Scripts that Want the behaviour:

using UnityEngine;
using System.Collections;

public class RandomScript : MonoBehaviour {
	void Start(){
		EventManager.EventContainerOne += NormalFunctionOne;
		EventManager.EventContainerTwo += NormalFunctionTwo;
		EventManager.EventContainerTwo += NormalFunctionThree;
	}
	void NormalFunctionOne(){
		Debug.Log("Func 1");
	}
	void NormalFunctionTwo(){
		Debug.Log("Func 2");
	}
	void NormalFunctionThree(){
		Debug.Log("Func 3");
	}
}

Now each time you trigger one func 1 will appear.

Each time you trigger two func 2&&3 will appear.

This is because there are 2 pointers inside EventContainerTwo.

Another thread regarding events&delegates and their uses can be found here

Sources: