How To Build An Event System in Unity

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there i'm matt and welcome to game dev guide this week we're taking a look at building a custom event system for your game we'll look at how to build one and why doing so might be useful but first we're going to have to take a small diversion and talk about Singleton's and dependencies if you're not already aware a singleton is a design pattern that restricts us to having one singular instance of an object if another object in our code needs some data from that object we call upon the singleton instance to refer to it Singleton's are incredibly useful for getting access to classes that you know you're only going to have one instance of this is most notable in unity when you call code like camera main or event system current the design of the engine expects only one of these classes to be active at any given time in your project so we can get a reference to it with a simple call like this with that in mind let's talk about dependencies let me explain a typical scenario and see if you fall somewhere into one of these two categories in unity you're probably relying on one of two things to be able to access data from another class or object you've either got a bunch of public properties in mono behaviors that you can assign in the inspector to get a reference to something or you're using a plethora of Singleton's frequently in your code to get the data you need for your various components and objects in your game odds are that most of us would usually fit somewhere in that spectrum regardless of where you are positioned you're sitting in a big bowl of dependency flavored spaghetti code and the moment you tweak remove or refactor one of those scripts you're probably having a bad time this is especially the case on large projects where bloats a real problem code can spiral out of control quickly and dependencies can stack faster than the professional cup stacking champion yes that's a real thing look it up it should be pretty clear from this that anything we can do to mitigate dependencies in our code base is a good thing so this is why we turn to a custom event system a custom event system is a form of observer pattern this is where an object also known as the subject maintains a list of its dependents known as observers then if a state has changed the subject notifies all of the observers offset change usually by calling their methods so for our event system we're going to create methods that are scripts can subscribe and listen to then in our game whenever something happens that our observers are listening for will tell the event system to dispatch that event if you've ever used a Unity action or the event trigger components in the inspector these are using a very similar methodology just that our event system will be a single object for all of our code to point and talk to rather than being spread across multiple components I've got a scene here with a little cue and I've got a wall and the door that I want to open when our cube enters the trigger area we're going to do all of this using our event system meaning that none of these objects will depend on one other existing for any of this to work let's start by making a new game object and adding a new script called game events with the script open we'll start by making a static singleton reference to the script yes I'm aware of the irony now we'll define our first event which will be one that comes from a trigger point beside the door so we'll create a public event action called on doorway trigger enter will then create a public method called doorway trigger enter and we'll check to make sure that the action isn't null before invoking it next we'll need to get our objects to subscribe to the event first let's create a method on our door that listens to the event and opens when it's dispatched from the start method we'll call the event system and will access the on doorway trigger interaction like this as you can see because we've defined the action as an event we can't just equate a single method to it it will only allow our methods to be subscribed and removed so we use the plus equals operator instead which basically just means add me to your list of subscribed events then we'll simply tween our door upwards when the event is triggered so now that we have the event listening we need to trigger the event itself over on our door trigger we'll add an on trigger enter method then we'll simply call the event system and tell it to dispatch the event we can see that the event system is triggered and the door opens let's repeat the whole process by adding another event into our event system that will tween our door to closed again if the trigger is exited and as you can see we've managed this with only the event system as our single dependency if I remove or delete any of these elements everything will still carry on running smoothly similarly if we duplicate our door and trigger a few times to make a series of rooms we can see that we don't need to do anything extra to get this to work it's handled by our event system automatically but now this causes all the doors to open you might be saying what if I want to link a door to a specific trigger well that's a great question friend let me show you the beauty of our custom event system is the ability to pass parameters into actions so let's add an integer into our actions and force this to be passed by the methods we need to go through and update our subscribe and listener methods in our scripts to match this change unfortunately we can't escape all dependencies we'll also need to set up an index ID property on our trigger and door and then we'll check that if the ID that's passed by the method matches the one on the door Open Sesame [Music] and there we have it we've now got events that are still agnostic but they're using parameters passed into them to handle their behavior locally one final thing it's really important to unsubscribe the event from the event system when the object is no longer needed or when it's destroyed otherwise you'll be running into a large number of null pointer errors and as you can see here if I delete this door while the game is running and then walk into its trigger it's not pretty so let's go into our code and add a method to our door that unsubscribes from our event system when it's destroyed clean code is important especially with systems like this so just be vigilant and try to remember to stay on top of it on a side note you might be wondering if it's possible to give events a return type using the func class you can have an action give either a return type or a return type and parameters for instance if you want to return a list of doors that are currently in the game it would probably look something like this I would recommend limiting func events like this as much as possible and you probably want to have a single script subscribing to the event to avoid any issues but for the sake of the topic that's how you'd approach it and that's about all there is to it when it comes to building a custom event system simply create an event system class and have it hold events relevant to your game logic then whenever you need scripts to talk to one another subscribe and dispatch the event system it's a much cleaner and much more flexible solution to passing data between objects in your game ultimately there's nothing wrong with using multiple Singleton's in your codebase however building an event system like this should help you cut down on unnecessary singleton instances and reduce heavy dependencies within your code if you've enjoyed this video and found it useful be sure to hit the like button and let me know what you think in the comments below and of course if you're interested in more game dev tips tricks and tutorials be sure to subscribe I'll see you next time thanks for watching you
Info
Channel: Game Dev Guide
Views: 333,427
Rating: undefined out of 5
Keywords: unity, learn, games, gamedev, how to, making games in unity, tutorial, unity tutorial, learning unity, unity3d tutorial, programming, making games, software, game engine, event system
Id: gx0Lt4tCDE0
Channel Id: undefined
Length: 8min 0sec (480 seconds)
Published: Mon May 06 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.