"Unity Events, Listeners, Delegates, etc." (595016)

Hey everyone,

I have some difficulties about understanding all the differences and usages of Unity Listener, Unity Events, Delegates, C# Events.

Could someone help me a bit about clarifying this ?
Thanks !

Ok, delegates are a way to have methods that can be assigned at runtime to variables. You can invoke that variable as if it was a method.

Events are delegates that can have more than one handler - I.e when you invoke a delegate marked with the event keyword it could call 20 functions. You can register and unregister methods to an event with + and - (Its very important to unregister an event if the object which has the method to be invoked has a longer lifetime than the object which contains event variable)

Unity events are Unitys implementation of a event system (I guess they use C# delegates internally?) . Its used a lot by the UI stuff. A major advantage is that you can asign handlers to UI events in the editor. These are serialised and saved. I havent seen a way to serialise C# events yet. Although, I am sure it is possible.

Actually delegates can be multicast as well. The main use case for an event over a delegate is an event exposes less control to outside classes. External classes can only subscribe and unsubscribe. They can’t do dumb stuff like clear all of the other subscribers with an assignment call, like you can with delegates.

UnityEvents have a few more advantages over traditional events. They are serialisable in the inspector, making them easy to edit. They also respond better to destroyed objects then regular C# events do.

2 Likes

Really? Wow, shocked I didnt know that. 8 years using c# …

1 Like

I need help guys i have no idea what i’m doing here… All the way from Africa
i am getting an error in my WinMenu script (underlined)
error message>>
Assets/Menu/WinMenu.cs(21,72): error CS1660: Cannot convert lambda expression' to non-delegate type EventBus.EventListner’

WIN MENU

void Start()
{

WinMenuPanel.SetActive(false);
GameManager.Instance.EventBus.AddListner(“OnAllEnemiesKilled”, () =>
{
GameManager.Instance.Timer.Add(() =>
{
GameManager.Instance.IsPaused = true;
WinMenuPanel.SetActive(true);
}, 4);
});
BackToMenuButton.onClick.AddListener(() =>
{
SceneManager.LoadScene(“MainMenu”);
});
}
}

EVENTBUS

internal void AddListner(string v, Func p)
{
throw new NotImplementedException();
}

private Dictionary<string, IList> EventTable
{
get
{
if (m_EventTable == null)
m_EventTable = new Dictionary<string, IList> ();
return m_EventTable;
}
}

What am i doing wrong here??
>>All the way in Southern Africa