Learn to Program with C# - DELEGATE & EVENTS - Advanced Unity Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up guys it's John here it's been quite a while since I've made neat YouTube video I've been wanting to get back into for a while so I thought I'd pick up where we left off with the advanced series for programming concepts and what we're going to be focusing on today is called the observer pattern which uses delegates and events to basically create a callback system a callback system is basically after some code runs you want to be notified that that code is finished you can use a callback system which then would trigger a function or several functions to be called so there's two parts to this you have a delegate which is a signature for an event a delegate basically holds a reference to a method or several methods then you have an event and the event is used to raise events and basically permits the action of calling the delegate reference with events you can subscribe to those events to add or remove methods right so delegates are multicast which means you can have multiple functions held inside them when that delegate is called through the event all of those methods will be called so delegates and events are advanced topics they're necessary to understand how to use um throughout my days as a software engineer I don't think I've ever created a project in a professional environment where I haven't used um delegates and events they are great concepts to work with they allow extensibility when you're creating frameworks and what we're going to do today as an applicable exercise is we're going to create a program where when you hit the space key we're going to subscribe to some events we're going to change the color of a few cubes okay so let's go ahead and look at how we go how we declare an event or a delegate first it's going to create a new C sharp script go ahead and call this callback system something's compiling in the background here there we go go ahead open that up in monodevelop or visual studios all right so what we have here is we have a callback system now the first thing I want to show you is a delegate all right in order to use delegates it requires the system namespace so we're going to go ahead and say using system and a delegate like I said before is just a reference to a method or several methods right what's important about delegate is the Declaration of it so we say public delegate void because we're not going to return anything if I was going to return something like if I wanted an int back or if I wanted a color back I would say public delegate color public delegate int but I don't want anything back I just want to run a method and I'm going to go and say punk delegate void and then it's just like a function what is this going to do we're going to go and say on let's say on message receive let's call it alright and then you initialize it just like that this is the Declaration of a delegate now what's important here is this part this is the signature of a delegate which means that we can assign the on message received delegate to hold any function we want with that signature void function name no parameters so for instance I can assign it to void start at your side to avoid update let's go ahead and do an example here where I have a void let's go ahead and say void right message alright this signature matches this signature which means if I were to create a reference of this delegate saying on message received it's going to want test I can assign this delegate test to write message because the delegate signature matches so I would say here right message oh my god right message and then just like that you don't own it shows it you don't need the parentheses just like that now what I can do is I can call that delegate just like a normal function so when I call test I can go ahead and say here debug that long or say right message call all right and if we go to unity here make sure that that script is on main camera and when I run this you're going to see that right message was called because I assigned that delegate to this so that's declaring the delegate I delegate is just a reference variable that is assigned a method and when I call that variable I can call it just like a method and it's going to call whatever method is assigned to test just like you see here now where this really comes in handy is when we use this with events and events allow us to subscribe and do subscribe to messages this is called the observer pattern right we're basically have a publisher and a subscriber the publisher is this guy and the subscriber is everyone who wants to be notified of an event that occurs all right so check this out let's go ahead and create an event here call public events and this is where it's important to use the event keyword and then it has to match the signature of the delegate which is this on message received so public event and then here we would say on message received that's the type of event we're looking for it's a signature that we can accept and then you give it a rate and a name so we're going to say here on let's go and say on compute right and you just initialize it like that you don't need the parentheses and like that it's just like this on complete now in order to make use of this what we're going to do say I want to subscribe on complete to write message function and if we were in a different class you could do this to you and I'll show you that when we create the actual project what I could do here is I could say autocomplete plus equals which is going to add a method can add right message just like that now when I call on complete just like a function it's still going to call right message check this out right in here let me go ahead and clean this so you can see it and you'll see here it did the exact same thing so now why use what's the point of the event right so the event basically is used as a subscriber base so for instance again you don't want to necessarily access this delegate as a standalone what the event allows you to do is allows you to subscribe and do subscribe methods at runtime anytime you want so for instance say you're having artificial intelligence right say your enemy is getting damaged and when it hits below 30% meaning it's almost about to die you could have an event callback where other enemies within the area are listening for an event and what you can do is you can fire off this event in all those enemies when the health gets below 30% will be notified and they'll come to your current location so that's what the events for the event is used to basically raise events all right and they work hand in hand with the delegate because we can't rely on the signature of that delegate and base it's just a clean way to do it honestly you can do everything with just a delegate but the pattern uses the event system so let's go ahead and actually look at creating an applicable use for this okay so say our program here ok is going to be when we hit the space key I want to turn three cubes whatever color I want them to be at that time okay so check this out I'm going to delete this script here let's go and create an input script for the user for when I hit space key alright so we're going to have a player script going to player okay all right and then let's go ahead and create another script and call it cube so fo our enemy and such we call it enemy all right so every enemy is going to have this script let's go ahead and create three cubes all right so we have a cube one cube - all right so let's go and rename these guys to enemy already rename them to enemy um then what we want to do is you want to select them all and go ahead and drop the enemy script on them so now what's happening here is every enemy has this enemies script right so what we want to do is in the player class when we hit space key we want to basically update the enemy color so how would we do that without delegates an event well to start we need to know when we have the space key so here if we hit the space key all right we hit the space key what do you want do you want to turn all those cubes red in order to get those cubes I need to know about them okay which means I would have to have here a public game object array so here we would have pumpkin mountain with site enemies or I could actually make it type enemy and then here I would go through each enemy so it's like here of our enemy and enemies and what I would do here is I would say enemy dot get components I want to render off it and then I want the color property and I would say here color dot red okay so when I hit the space key I'm going to go through all the enemies and I'm going to turn them red in order to make that work we have to go to our main camera click on the player you have this array let's go ahead and drop all three of these enemies in there so you're just going to drag them in one two and three so now we have a reference to those guys and now when I hit the space key all three of them will turn red I'm going to space them out event okay when I have the space key they're all going to turn red there yeah now that's a perfectly fine way to do it okay there's nothing wrong with this and if you wanted to make it even better you can go ahead and take this you can go and refractor it um which I believe where is factor and then this hold on um that's super annoying I don't see it right now oh here we go quick actions in refractory so what I can do here is I can go ahead and say we do want to extract the method and what it's going to do now is you can call this change color and we're done all right now all we did here is we just refracted it and it's more clean so basically my neck is basically I call this change color method and this happens that's perfectly fine no problems here however there's a more efficient more reliable more just overall more performance friendlier way to do this so I'm going to go and delete everything we just did there and I'm going to use a delegate and event system for this so check this out the player has a delegate here that's going to basically change the color of the enemies okay and we could even change them every time we hit the space key so like for instance say every time you damage them you want them to turn red you can do that through a delegate an event so here we're going to have here a public delegate type void alright so probably delegate void and then what are we going to do we're going to call this let's go and call it a public delegate void we're going to say on enemy their plugs on get void change enemy color okay is what the delegates cold we're going to pass in a reference to a color okay so public delegate void change enemy color um and then what we're going to do here is we are going to say public event and the event name has to match the signature of the delegate so here change enemy colored oops the name of this so change on the color and then we're going to call it on enemy kick now the reason why we're calling this on an enemy hit is this is what's going to get called every time the enemy is hit so let's go ahead and save this hop of your enemy right here we go the enemies have a damage function okay never damage function now every time the enemy gets hit we want to call this damage function right so how can we do that that's what the whole thing we're doing here every time the enemy is hit we want to call this method right the damage function and to damage the enemy we're doing it every time you hit the space key so every time with the space key again with enemy to do that before we'd have to loop through each one and call their damage function well we no longer have to do that there's a damage method here and what we're going to do here is we're going to go ahead and take we're going to find this event okay we're going to find that event we're going to subscribe this damage function to it so in order to do that the enemies need to know about the player so let's go ahead and turn the player here into a sink all right I went ahead and created that singleton here so that the enemies will be able to access the player more easily if you're not familiar with Singleton's go ahead and watch the singleton video in the intermediate course to get a better understanding what I wanted what I've done here is I wrapped it up in a rigid tag to basically clean up my code a bit so now that the enemy can access the player by just typing player dot and getting all the public information there's one more thing we need to do in order for events to work they have to be of type static just like it's similar to names to be static so that they run along all instances of class just so that they're available when you need them so by changing that the stat we can actually go ahead now from the enemy class we can call player dot on enemy hit now notice that lightning bolt symbol that lightning bolt symbol signifies that this is an event which we can subscribe to whenever we call that event on enemy hit we can say hey I want some method to be called so in our case it's going to be this damage function so what we're going to do now is we on start of the game we need all of our enemies all three of them which is what the script is we need to register to this on enemy hit event and the method we're going to register to is the damage method and all you have to do is just type it like that so the reason why we can do that is because Dan because here void damage color color matches this signature function name type void parameter color okay um so here what we did is we have gone ahead and we have subscribed the event now what's important to do here is we need to actually go ahead and change that color so we're going to say here transform to get the current enemy we're going to say get component we're going to set the renderer this object and we're going to go ahead and say here we're going to get the material in the color property and we're going to say equals the color that we pass in okay so whatever color we pass in is the color this enemy will change to so how do we actually use this now we come back here to where we damage the enemy and what we're going to do is we're going to first check to see if anyone has subscribed to the on enemy hit so to do that is we're going to check if on enemy hit is not know if it's not null that means that there are people listening for this event so every time we hit the space key we're going to call on enemy hit and we're going to pass in a color let's go ahead and make them color not red every time I hit the space key save that you go to unity here you'll notice they each have the enemy script on start they get subscribed and what we're going to do is I hit space they alternate see how much more efficient that was versus using a 4-inch loop now there's a few problems with this we can create what's called a memory leak let's say you're damaging them and you removed one so let's go ahead and turn them red now say we killed an enemy and I hit it again I say space key you're going to see here that we have an Emer at an enemy leak the object of type enemy has been destroyed but you're still trying to access it your script should either check if it is nowhere you should not destroy the objects what we've done here is we created a problem in order to fix this when an enemy is destroyed we need to unsubscribe from it so here is where we're subscribing we need to say void on disable this method is called automatically when an object is destroyed we need to go ahead and say here player dot on enemy hit - equals damage now we have unsubscribed from that function it is now okay to delete this object so check this out I'm going to go ahead and save this we're going to do the same exact test right I hit the space key they turn red I'm going to go ahead and delete one of these guys I'm gonna hit the space key again no errors okay because now we have successfully unregistered so just to give you guys some use cases for this a lot of times you'll see it used in any time you need a call back any time you want to know if something has happened or something they don't complete you can create a call back system oftentimes what you can also do is for artificial intelligence like I was talking about before it's great to use if you want to help have have a smart AI so that when your enemies need help it can it can register system events and the surrounding enemies can get notified hey my health is below 30 come get me you know come save me well yeah there's a lot of things you can do with delegates and events it allows for a lot of flexibility in your program so let me know what you think of this video what this topic is introducing you to is more advanced knowledge what we're going to be doing in the future videos is we're going to look things called lambda expressions anonymous methods we're going to look at action and funk which are equivalent to delegates and events but in a simpler syntax and we're also going to get involved with link which is basically querying um databases or data structures so we got a lot to cover I'm looking forward to being back in the you know the hang of things with making videos my goal was to try and complete a video once a week not necessarily programming programming related although I am going to continue making programming content and game development content but I'm also going to start creating videos about some of the awesome tech I've recently purchased so stay tuned for that but thanks for watching guys and I will see you next time
Info
Channel: GameDevHQ
Views: 75,794
Rating: undefined out of 5
Keywords: unity, unity3d, delegates and events, delegate events in unity, c# delegate, delegates and events unity tutorial, unity event system, how to use delegate and events in unity c#, observer pattern in unity, unity callback system, callback system in unity, c# events, actions vs delegates c#, how to use delegates in c#, what are delegates c# unity, action and func c# unity, c#, tutorial, howto, gamedevhq, observer pattern c# unity, c# callback system in unity, c# event, events c# unity
Id: qwQ16sS8FSs
Channel Id: undefined
Length: 19min 53sec (1193 seconds)
Published: Wed Dec 21 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.