Creating Custom Unity Events!

Marcus Ansley
2 min readMay 9, 2021

--

Sometimes we’ll find a standard event doesn’t quite suit our needs. It’s all well and good broadcasting a method call of sorts, but what if we want some information to get carried across, like a boolean, string, or even a struct? That’s where we might get into one of my favourite parts of this topic: creating custom UnityEvents. The syntax is a bit different for these, but once we get past that there’s a whole world of opportunities these allow for:

Assuming we have this on a static instance of a class, such as a ‘GameEvents’ class, all we need to do to make use of these events is make a call like GameEvents.current.PlayerKill(3) or GameEvents.current.PowerupCollected(powerupType.ToString()) (most likely from the Player class in this case). Then we just need to ensure the object which need to listen to the events are listening, and have an appropriate method (accepting either an integer or string parameter here) which will be called:

(I’m unlikely to have these two methods on the same class, so this is just for demonstration 😉)

As mentioned, we could also pass in something a bit more complex, for instance a struct. I’ve worked on a project recently where I needed an AudioController to create an AudioSource every time an object in the scene is pressed, and these objects would use a custom event to broadcast a struct containing information on what AudioClip, AudioMixerGroup, and settings (volume, pitch, etc.) needed to be used.

Important Note!

As with regular events, we do need to unsubscribe any objects listening to events if we intend to destroy them. Again, the syntax is a little different to what we use with regular events, but we can still implement this in much the same way using the OnDestroy method:

And with that, I think that’s about all I currently have on the subject of events 😉 There’s still quite a bit for me to learn, as I’m not entirely sure about the difference between UnityEvents, Actions, and Delegates, and I’m also not convinced some of my implementation of events is the tidiest, but I’m hoping to learn some more about that as I go!

--

--

Marcus Ansley
Marcus Ansley

Written by Marcus Ansley

Game Developer | Game Design and Literature Graduate

No responses yet