Simple event system in Unity

You must use UnityEvent.

public UnityEvent whoa;

It is dead easy.

Make a script BigScript.cs

using UnityEngine;
using System.Collections;
using UnityEngine.Events;

public class BigScript:MonoBehaviour
{
    [Header("Here's a cool event! Drag anything here!")]
    public UnityEvent whoa;
}

Put it on a game object. Now look at it in the Inspector.

You will see the "whoa" event.

Simply drag your other scripts to there, to make something happen, on those other scripts, when "whoa" happens.

enter image description here

It's that simple. To call the event in BigScript, it is just

    [Header("Here's a cool event! Drag anything here!")]
    public UnityEvent whoa;
    
    private void YourFunction()
    {
        whoa.Invoke();
    }

In rare cases you may need to add a listener via code rather than simply dragging it in the Editor. This is trivial:

whoa.AddListener(ScreenMaybeChanged);

(Normally you should never have to do that. Simply drag to connect. I only mention this for completeness.)


That's all there is to it.

Be aware of out of date example code regarding this topic on the internet.


The above shows how to connect simple functions that have no argument.

If you do need an argument:

Here is an example where the function has ONE FLOAT argument:

Simply add THIS CODE at the top of the file:

[System.Serializable] public class _UnityEventFloat:UnityEvent<float> {}

then proceed as normal. It's that easy.

// ...
using UnityEngine.Events;

// add this magic line of code up top...
[System.Serializable] public class _UnityEventFloat:UnityEvent<float> {}

public class SomeThingHappens : MonoBehaviour
{
    // now proceed as usual:
    public _UnityEventFloat changedLength;
    
    void ProcessValues(float v)
    {
        // ...
        changedLength.Invoke(1.4455f);
    }
}

When you drag from your other function to the Editor slot on this function:

Be certain to use the section - "Dynamic float".

enter image description here

(Confusingly your function will also be listed in the "Static Parameters" section! That is a huge gotchya in Unity!)


Don't worry too much about the number of subscribers if you are only talking about a few dozens. Yes, once you get into the hundreds or thousands it might be a good idea to optimize this, but even then. First rule of optimization: don't optimize.

So: just have every instance subscribe to the event and be done with it.

Tags:

C#

Events

Unity3D