Unity – UnityEvent

What is a UnityEvent?

A UnityEvent is Unity’s built-in event system which allows you to subscribe to events right in the editor. The Unity UI system commonly uses them for example when a button is pressed:

How do I use a UnityEvent in my code?

All you need to do, is create a public UnityEvent at the top of your script. You will then be able to see it in the inspector and subscribe scripts to receive the event.

To call the event so that other script receive the event all you need to do is call the name of the UnityEvent and .Invoke() on it and it will then send the event to the subscribed scripts.

Can I create an event and pass a parameter to any function which subscribes?

Yes. What you need to do is create a class which inherits from UnityEvent. UnityEvent is a generic class so you can pass parameters like so:

Where float is the parameter type which will be sent. The class must also be ‘Serializable’ which allows the Unity editor to display it in the inspector.

How do I set up a function to receive an event?

It is super simple! Within any other script simply create a public method which matches the same parameters as the event. Then attach the script to the event in the inspector like so:

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.