Today’s post isn’t directly related to VR, but it is a technique I use in all the VR apps I build in Unity3d which produces cleaner code.

It’s very common to have code that is waiting to receive an event and when it occurs to go and do something about it.

Unity game objects have the SendMessage, SendMessageUpwards and BroadcastMessage methods to send an event up or down it’s game object hierarchy.  But these are generally discouraged because the event is a string and there is no guarantee you didn’t put in a typo.

Unity C# code has delegate events for adding/removing event listeners and then handling the code. With those you end up with code littered with linkages between classes which can make it harder to maintain and test your code.

Unity Events

Unity has another type of event based on the class UnityEvent. The UnityEvent object is supported in the scene hierarchy so you can add/remove event handlers in the inspector without writing any code!

The advantage is it is easy to fire events, and easy to wire up event handlers in the scene. It keeps component linkages separate from the code.

Here’s what publishing an event looks like:

using UnityEngine.Events;

public class ExampleFiresEvents : MonoBehaviour {

    public UnityEvent onSomethingHappenedEvent;

    void Update () {

        if (Input.GetButtonDown ("Fire1")) {
            onSomethingHappenedEvent.Invoke ();
        }
    }
}

And then add a public void SomeMethod() method call in another c# script attached to a game object. Then use the inspector to wire up that game object and choose that method to receive the event:

UnityEvents

 

That’s it, simple call Invoke() on your event and all event listeners will be called.

Internally, I believe this still uses the c# delegate system, which is why if you want to add/remove listeners via code, you can still do that using AddListener and RemoveListener.

Demo

https://docs.unity3d.com/ScriptReference/Events.UnityEvent.html