Can I use a delegate/event in Unity3D?

In Unity I see this type of code a lot for wiring up code for events:

        Button myButton;
        myButton.onClick.AddListener(delegate( string aText ) {
            // Some Action

Where we add a listener to an event. Coming from the C# world to Unity, I am used to writing code with delegates and events like this:

        public delegate void ValueChanged(string aText);

        public class ButtonRoot : MonoBehaviour {
            public event ValueChanged onValueChanged;

        ButtonRoot DeckButton = new ButtonRoot;
        DeckButton.onValueChanged += delegate( string aText ) {
            // Some Action

Is there some reason why I should not use the Event/AddListener vs. the C# event/delegate mechanism?

There are two main from-the-box mechanisms of subscribing to something in Unity:

  1. Traditional C# event delegates. These are non-persistent within the Unity’s serialisation system. At least not from the box. These delegates are fast. I would personally use these delegates only in programmer-to-programmer cases.
  2. Unity Events. These are persistent within the Unity’s serialisation system and exposed in the editor/inspector. These are not really serialised delegates, but serialised observers. Also note that these unity events support both persistent callbacks (specified only through the inspector) and non-persistent callbacks (specified through AddListener/RemoveListener). There might be a way to add persistent callbacks from code two, but that’s not the AddListener method, something else, maybe even UnityEditor-only. People very often associate these events with Unity’s new UI system while the truth is — they aren’t. They are completely UI agnostic and are on their own. Unity is to blame for very poor naming here (EventTrigger, EventSystem, etc.). These events are much slower. I would only use these delegates to expose event subscription to non-programming folks to enable visual logics/flow authoring. Like linking some sounds on when some monster kicked some other monster.

It just coincides so, that Unity uses Unity Events in their own new UI system. So it’s not like you have choice, you have to play by their rules within the UI code. Apart from the UI, as I’ve already stated, I’d recommend to keep traditional delegates for code-only things, and persistent/serialised delegates for enabling visual logics/flow authoring. In fact I find it cool to have two different mechanisms of event subscription, one for programmers, and one for designers.

Apart from these two mechanisms there are tons of third party solutions of different grade of quality in the Asset Store and on the Internets.

But to your question: the reason you should favour one to another depends on what you’re trying to implement.

sure you can