Decoupling via UnityEvent
I recently being experimenting with using Unity’s association of script and hierarchy to create different software designs. What I failed to realize was the hidden power of the UnityEvent.
Consider this Coffee Button script as shown in the inspector.
I had being thinking about the possibility of exposing an Action property so you could drag in other scripts to form a chain. So in this case if I wanted other scripts to run when the Coffee Button is pressed I would add to a list of Actions. That way I don’t have to edit the code to manually subscribe to the event. I realised that this seems very similar to how Unity provides Button Click events in the UI. However, I didn’t realize that this functionality is exposed by UnityEvent. Consider the following event property;
[SerializeField]
UnityEngine.Events.UnityEvent OnCoffeeSelected;
Adding the above code exposes the same Inspector as you see with the UI elements.
So now I’m free to drag in any other script and now any other matching function too.
The internal code works exactly the same as regular event.
OnCoffeeSelected?.Invoke();
Whilst using UnityEvent isn’t for free, the inner workings are more complex, and probably slight less performant, than a standard event but regardless it adds an interesting tool to the software designers kit.