What are Events? (C# Basics)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we're going to go over what are events in c-sharp how they work and how they're used we're going to see the benefits of events and how they are essential to keeping our code nice and clean but Vienna [Music] hello and welcome I'm your code monkey and this channel is all about helping you learn how to make your own games with enough tutorials made by a professional indie game developer so if you find the video helpful consider subscribing okay so if you've seen a bunch of my videos you've probably heard me mention two things one I always highlight the importance of writing clean code and two I use events to d-cup on various systems and keep my code clean if you want to write good quality code you need to learn and use events the good thing is they're actually very easy so events aren't just a way of saying something happened without knowing or caring about who is listening if anyone you have publishers and subscribers the publisher has its event and these subscribers can subscribe to that event multiple subscribers can subscribe to the same event then when something happens the publisher fires off the event and all these subscribers get notified that the event was fired the key thing is that the publisher does not know who these subscribers are so there might be lots of them or there might be none they might process the event or completely ignore it the publisher doesn't know and doesn't care who is listening and what they did with that information so this allows you to write code in the publisher that is decoupled from whatever other code you also want to run that isn't essential this video is made possible thanks to these awesome supporters go to patreon.com/scishow to code monkey to get some perks and help keep the videos free for everyone one way you've seen me use events a lot is to keep the illogic and visual separate normally you don't want your logic code to be tightly coupled with the visual you want a logic to work on its own regardless of whether or not there's a visual component the visual should just display what is happening inside and logic so to keep those separate the logic class fires off events which may or may not be caught by a class at Hamill's the visuals for example I made the unlevel system quite a long time ago and as always implement the logic and events and connected that test visual to those events and recently I made a video on a skill tree and I use the exact same level system class the difference is only individual on the level system I had a dummy character some buttons and a bar and on the skill tree I have a moving player and the experience bar with a level counter since I used events I didn't have to modify any of the code inside the unlevel system because I use the same logic and only change the visuals so using events allowed me to very easily reuse that class in a completely different project all right let's look at some code so over here I have my basic script now the way you define an event is very simple first you define the accessor so in this case let's make it public and then you use the event keyword so this is how you define that this film is going to be an event then we need to know the type and now the center time for events as used in the.net standard is the event handler which is inside using system now if an handler as you can see it's just a simple delegate with two fields we have an object for the center and the event args which we'll cover in a bit so we define the type and then we just pass in the name so in this case um let's call it on space press normally you also name it starring with on and then whatever it represents so on space pressed on enemy killed on play win and so on so here we have defined our event now let's see how we can trigger and how to subtract first let's do the trigger so in here let's make our update function and let's test for the spacebar bring down and when we press the spacebar and let's fire off our event so to do that we call our event as if it were a function so on space pressed and we just count now for the similar let's just pass in this and for the event args since we don't have any extra information we can use the constant event our X dot empty and that's it so over here we are firing off our event whenever we press the spacebar so let's try it out okay here we are the game is running here is the console and press space and there we go we have an error we have a known reference exception now the reason is because right now we do not have any subscribers so the underlying structure for our event is set to no so when we fire an event we need to first test that the event is not know so if on space pressed if there is not now then we actually do fire off our event now I can press the spacebar and there you go we do not have an error and since C sharp 6 we can shorten this in order to use the null conditional operator so we just do question mark and then call invoke so this does the exact same thing it invokes event only if on space pressed is not no and again here I am and I'm pressing space and there we go no errors awesome so now that we have the event being fired let's do something with it now in order to subscribe to the event first we define a function that will receive that event now the function signature needs to be the same as event so in this case we're going to make a function that takes a object and the event args parameter so here we have our function which matches this signature and when we have different relatively simple debug log ok now in order to subscribe we access the event so on space pressed and we do plus equals and we add our function so this is how we add our function onto this event so when this event is invoked it won't call the functions attached to that event which in this case is this function so when we press space it's going to run this code and do a lock let's see so here we are and now I press space and there yo we have our log so our event is being fired when we press space and it's being captured by that function which then does a lock ok great now here we are triggering and listening to the event on the same class but the benefits are when we listen from somewhere else so let's do that in the editor and let's make another script and let's attach this script into the same game object ok and now in here first we need to get a reference to our other script so since they're on the same game object we just do get component of our testing event script and now with this reference we can access our event on space pressed and just like before we do pause equals and then we add our function and now if you're using Visual Studio you can use code completion to really speed this up so we're here as you can see I can press tab and there you go it automatically creates the function and now here let's do the same debug log ok so that's it now back into the publisher script and let's get rid of this one so this script is only responsible for firing off the event and then this script accesses now one end subscribes to that event let's see okay so here we are in our press space any of there you go we have our message and if in here we remove the subscriber script and I'll run again and I press space and there you go we do not have any errors and everything is still running exactly the same so the publisher class does not require the subscriber to exist alright so here we have our example we have this class which fires off this event and this class is absolutely no knowledge that this other class exists so this one just fires off the event whether someone is listening or not which again this is perfect for separating logic and visuals you need visuals to know about logic but you do not want the logic to know about the visuals you want a logic to be able to work with or without the visuals so you just have your logic fair enough events in your visuals if they exist listening to those events now here we are subscribing to the event but as you can imagine we can also unsubscribe so uncertain let's subscribe and then after receiving the event once let's unsubscribe so to unsubscribe instead of pause equals we do minus equals so that's it let's test ok here we are and let's press space and there you go we have the unlock function but now press space again and there you go no more messages so we unsubscribed so we stopped receiving the events now in here we're using the event handler which as you can see has two fields an object and an event args the event Rx is the standard way for passing more information through the event so the way we do that is first we make a class that derives from event args and now in here we define whatever fields we want so let's say we have an end for this place County and now up here when we define the event we can use the generic version and pass in our specific event args as the generic parameter so in this case on Swiss press event arts so now our event won't contain an object of this type on the second parameter so down here you can already see the error in here we need to pass in of type on space pressed event args so we do a new and we create our object so just like that so whenever we press space we are incrementing this local field then we're firing out the event and constructing a on space pressed event args and passing in a specific parameter and now we go back into our subscriber and here we modify our signature to receive our new time and now we can access that new type and we can get for example D space count so just like this we're passing extra data along with our event now let's see so here we are in press space and yep there it is we have our event being filed and passing along some extra than that awesome now another thing about events is you do not have to use event handler this is just the normal dotnet standard events work with delegates and if an handler is simply D standard delegate so here we can define our own delegate so here we the finally delegate it returns void and takes a parameter for a float now if you're not familiar with delegates they are essentially function signatures let me know in the comments if you'd like to see a video dedicated just to delegates now we can make an event of this time so again we passing the event keyword and then our specific delegate type and we can fire up very much in the same way so we can't invoke and in this case we take a fold parameter okay so we have our event being fired and now back in the subscriber and here let's subscribe to our new event so on float event plus equals press tab and there you go there's our automatic event which as you can see takes a full parameter and just like that alright so let's test okay so here we are on press space and there you go we have our vent being fired on with a fault parameter and again if we're working with delegates then we can also use the default delegate called action so you make a public event and we can use the time action so action as you can see as you see don't forget that returns void and action also has a generic version so you can define it with a bunch of different types so in this case and what's the final action that takes a boolean and an integer and then down here we fire off the event just like we do every time so there it is we have our event working with an action that takes a boolean and an int and then here we subscribe the same way and let's test and here we are and yep we have all of our events working so you can see how you're not forced to work event handler you can use whatever that'll get you want personally I like to stick with the standard so use event handler and then if I need extra info I create an event arts but you can use whatever time we get you want now another thing specific to unity our unity events these were pretty much the same way with difference being that they are shown in the editor so in here we make a public of time unity event and unity event is inside unity engine that events so here we have our unity event then we invoke it exactly the same way so we called out invoke in this case we have no parameters and also note how this does not have the event keyword and now if we go back into the editor with our object selected you can see over here in the inspector we have a field for our unity event so we can click the plus icon and in here some liked an object so let's select this same object and then we can select a function from that so let's make a function to call here in our subscriber script let's make it so here we have a function with no parameters returning void and it's public and now back into the editor over here we can select that function so click in here then we go into our script testing event subscriber and down here we have our testing unity event function so select it and now let's tests so here we are in press space and if there you go everything is working correctly here we have our testing unit event main trigger so the main benefit of unity events are that you can easily set them in the editor so if you're trying to make your game more fun to designers this may be a good tool alright so here we looked on how events work how they're used and what are the main benefits as you saw events are excellent for helping you keep your code nice and organized it allows objects to work with other objects without being tightly coupled this video is made possible thanks to these awesome supporters go to patreon.com/scishow to code monkey to get parks and help keep the videos free for everyone as always you can download the project files in Italy's room in tucumán calm subscribe to the channel for more unity tutorials post any questions I have in the comments and I'll see you next time [Music]
Info
Channel: Code Monkey
Views: 227,135
Rating: undefined out of 5
Keywords: unity event system, unity event, c# event, c# events, c# eventhandler, code monkey, unity c#, brackeys, unity tutorial, unity game tutorial, unity tutorial for beginners, unity 2d tutorial, unity 3d, unity, game design, game development, game dev, game development unity, unity 2d, unity 3d tutorial, programming, coding, c#, code, software development, learn to code, learn programming, unity publisher, c# delegate, events, delegates, unity action
Id: OuZrhykVytg
Channel Id: undefined
Length: 15min 5sec (905 seconds)
Published: Sun Feb 09 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.