A delegate is literally a fancy, managed wrapper for a function pointer. You can even obtain a function pointer from native code and marshal it into a C# delegate, then pass that delegate around and call it just like any other delegate. This can also work in reverse. Under the hood, a delegate _is_ a function pointer, it just uses a different declarative syntax and hides the actual address and other complexities from you so it can be used more intuitively. I manually declare delegates sometimes, but many of the most common signatures you'd want to use already have a predefined version like a delegate void with no parameters or several parameters can be declared with Action and Action and when you want to return stuff there's Func and Func (there's variants with numerous parameters like T1, T2, T3, etc). That covers a _lot_ of delegate usage, and it's hard to think of some it won't cover. So why ever declare your own? Well, for intuitive and expressive naming, of course! It can clearly express your intent as a programmer and also make things a bit more type safe. You may not want to use Action for an event representing two totally different things so no one can confuse the two and create hidden bugs that can be hard to find. If it just uses an Action or Func, you can easily have another programmer mix stuff up and have criss-crossing events creating undesirable or fatal behaviors. But if you have two types of delegate clearly named things like _MenuActionDelegate_ and _KeyInputDelegate_ it gets much harder to confuse those things or use the wrong thing! That's a pretty contrived example, but in a real project you'll see how that makes sense if you think about it ... So, sometimes, it's actually kind of _smart_ to manually define a custom delegate, even if that signature is already defined by built-in ones like Action or Func. Keep in mind, there's _nothing_ special about Action or Func, they're just common delegate declarations exactly like the ones we declare ourselves. Many people don't know this and think those are some kind of special classes with their own fancy code but they're not. This is literally the definition of Action, as follows: public delegate void Action(T obj); That's it! That's the entire definition/implementation of Action, just a common delegate with one generic parameter. Nothing special about it other than what the .NET Framework does beneath the hood with _all_ delegates we declare. Microsoft just included these built-in delegate definitions so we'd all have predefined ones that cover almost all the use cases, so we wouldn't have to waste time or add clutter to code if it didn't make any sense to. If I want to quickly use a delegate in one place in my app and be done with it, I'd hate to have to stop and decide where I should go define a delegate signature and then come back to my method I was working on and use it ... much easier to just use a Func or something as a temporary use delegate. But anytime I'm creating something like a custom event system that's consumed from other classes, I do take the time to define my own custom delegates for the sake of clarity and expressiveness ...
P.S. - As always, enjoyed the video and enjoy throwing in my two cents on these topics. It's refreshing to see someone teaching important C# fundamentals and good practices in the Unity world, as there's so much awfulness out there, haha. I share these videos with junior devs on our team that are curious about the topics and want additional information and they enjoy these too! 🙂
im a bit confused. "So why ever declare your own? for intuitive and expressive naming" couldn't you just use the predefined types but name it something that wouldn't cause confusion? eg. public event action MenuActionEvent; i dont see the need to declare your own delegates if the predefined ones fit your need
So many people sound like they're just reading from the docs when teaching something. I'm always amazed at how you DON'T do this, but really deliver the material in an understandable way. Brilliant video.
I've been trying to understand exactly what a delegate is for far longer than I would like to admit. This clear and concise example at the start of the video just made it straight up obvious. Thank you!!
This video (and channel) is an absolute gold mine. I really wish this was explained like this to me earlier, it's so clear now. Thanks for taking the time to put this together, I will recommend this video to any confused beginners I might encounter along my way.
I love that you used real world practical gaming examples. Sometimes I learn about these new programming concepts but its not clicking why I would use them.
Loved that this is one of the first videos about events that the person mentions the downside of events/decoupling, which is lack of clarity, and harder debugging, so it's something to definitely use with caution, especially the "static" version of it, since you now can subscribe from literally any script without even holding a reference to a specific instance. Really nice video!
You've gotta love it when someone Really knows the subject matter, and how to relay it. That was an excellent explanation, thank you. You are a step above the other 'monkeys' :D
Well damn I wish I'd seen this years ago. I know how to use delegates but did not know that simplified way of writing them as Actions and static actions. Thanks!
There are 2 reasons why I use more rarely (static) events: the subscribing/unsubscribing part and the "voyeur"-ability this functionality gives - everyone can subscribe, also he can subscribe redundantly, but I don't want that! I want to limit access and know exactly who gets triggered and who listens - you clearly state it in the video => REDUCED CLARITY! (bravo for giving Pros and Cons on the concept!!!)
I've used delegates in my game mixed with interfaces to change the functionality depending on interactions. It's been super useful to allow my function to change and be called without me having to worry about what it is actually calling.
I already knew plenty of things about C#, but i could never wrap my head around how delegates work. Your video made it clear to me. Also, static events seem really useful for my stuff, and i cant really tell why i havent learned them before. Thank you! Best wishes!
I wasnt ready for this video when I first started watching but I have recently stated calling Unity Events so now I am able to understand this much better. Honestly your channel is amazing! Your personality is hilarious...love all the zingers!
I love the detail into C# in your videos. They have helped me strengthen my skills as a developer. I don't use Unity but I do use C# with Godot and your videos have helped me immensely. Keep up the great work and thank you for what you do!
Special thanks for the beautiful picture, beautiful buttons, beautiful sprites, in total - beatifull visual work in your videos which in no way relate to the topics of your videos, but it's very pleasing to the eye Probably this video not for beginners and your explanation not the best but doesnt matter, your videos so good It's like comparing buggy win 10 and mac os with amazing controls
In our workplace, we avoid using UnityEvent. This is because in the past we would spend hours debugging why Foo() is being triggered randomly only to see that Foo() is in a random UnityEvent in a random animation or prefab. The problem is that if a function is invoked by a UnityEvent, the stack trace will not say which object is invoking that function. The IDE will also mark the function as "not used" so it shows as greyed out and somewhere down the road, a new programmer works on the project and deletes the function tied to a UnityEvent causing all sorts of bugs. It's less designer-friendly but having functions be explicitly triggered through code only helps reduce bugs in general. This has somewhat been alleviated though ever since we all switched to Rider because Rider knows if a function is used in a UnityEvent.
This is a major problem for the entire scriptable object architecture workflow. It's toop hard to keep track of what's triggering what. I stick with standard functions, too.
I see some JB Rider shortcuts being used. I'd be interested in a video detailing some of the JB Rider tips as it relates to Unity development.. Maybe you can get them to sponsor the video or something :)
Really Helpful video, as usual, I recently found the 2048 and grid game video. Ngl those types of videos are really great for learning. I found it very helpful. Learned a lot, Thank you!!. Hope you make long videos like those covering a variety of topics.
One thing I like about Actions is that you don't need a definition like Delegates, just the signature. A good tip is that if you are going to create some kind of custom "EventArgs" to send a group of data, prefer to use struct unless a class is necessary, that will generate less garbage. (that is the struct's function anyway 😁)
Nice video and nice information regarding's this topics. I will have to work with them in order to understand them better but now at least I have a general understanding of them so thank you for this video :)
Shortest explanation about differences between delegates and events: An Event is a delegate with 2 restrictions: 1- You can not invoke the delegate reference directly 2- You can not assign to it directly A bit longer(but sweet and funny)explanation: czcams.com/video/NgrnCMaxIXM/video.htmlfeature=shared
Dude, you create insanely useful, extremely well explained videos! I like your short on-spot examples to demonstrate everything. Keep up the good work! I hope you make a cooperative video with Jason Weimann and Codemonkey, so your channel gains more popularity. In my opinion you beat both of them: Jason sometimes drifts away from the topic and Codemonkey's tutorials gotta always get paused to check what he speedtyped and moved off screen immediately after that.
@@Tarodev :D just don't watch the sequel. I am being honest with you, watching constantly tutorials for a decade (since Brackeys entered and basically (re)defined the gamedev youtube tutorial scene) in case there is something new in Unity that I missed. You are really good at explaining. Fact.
I try to keep the visualization / UI totally decoupled from game logic and Events (or UnityEvent more specifically) provide a good one-way communication between them. Though sometimes I run into a problem when subscribing and invoking happen in the same frame (new instantiated class subscribes to an event which invokes during the same frame - thus not triggering whatever function I wanted). Thanks for the video anyway! I've always found delegates to be hard to understand.
@12:30 About unsubscribing; Normally I subscribe and unsubscribe exactly like you suggest here (@13:12). But in rare occasions, I found myself having to subscribe to events from multiple locations in my codes. This easily lead to accidental subscriptions to the same event multiple times, which results in it being fired multiple times with each call. In situations like this, it is possible to unsubscribe first, and then subscribe in the next line. If you are not already subscribed, nothing happens. If you are, you make sure to only add one listener.
This is fantastic! You explain the subject so clearly, it helped me out so much. Do you have any plans to cover Observables in the future? I'm trying to learn it at the moment but there doesn't seem to be many tutorials out there that cover the subject in detail.
Great explanation! I became a huge fan of events since I discovered them, but at a certain point I also became too obsessed. As you say in the end, it's good to decouple things when needed but sometimes it might just make your game architecture overly complicated if you decouple too much. One question I have is: for objects that are constantly being enabled/disabled I usually subscribe to events on OnEnable and unsubscribe on OnDisable. But what about objects that remain enabled throughout the lifetime of a scene and only get disabled/destroyed when a new one is loaded? I usually subscribe on Awake, in those cases... but should I bother to unsubscribe on OnDestroy anyway?
I'm constantly disabling UI-elements and I have trouble getting events to work properly. I was wondering if instead of disabling/enabling, it was better to make the UI-elements invisible? But you claim here it works if you assign the subscription in the Awake? Do you mean C# or Unity-events, or both? P.S. If you know any good videos for learning proper UI-programming in Unity please share, I find it somewhat cumbersome or hard to wrap my head around.
Contrary to all the comments, I believe this tutorial works only if you already know events and delegates or at least are familiar with them, so I bit of constructive criticism I believe that it lacks explaining of how it works and why.
Was getting worried at the start there ... WTH I'm not using any of that, am I doing it wrong??... then Action ... ahhhh that's the one, ok good !! LOL.
Outstanding video!! Quick question, how is the extension/add-on called at 5:23 ? The one that gives you choices to autocomplete/etc. Is there an alternative inside visualstudio? Thanks a ton!
Hey Tarodev, awesome video. I've been working on an Event System in Unity that keeps track of all subscriber to debug them more easily. I just made a class with an action and a GameObject fields. But do you think the EventHandler could do the same ? Also I'm looking for a way to serialize them in the inspector (just like UnityEvents), have you any take on this ? I could just use UnityEvent from the start but runtime added callbacks are not serialized so that ruins the purpose. I tried a custom editor to get the data through reflexion but it's very hard to get the invocation list to show in the inspector in a good way..
To serialize standard delegates in the editor you'll nerd a third part library. Odin does it, but a package called UltEvents does it significantly better
@@Tarodev And it is even free, wow ! Thanks for the reply ! I used the Odin serialization and managed to have a working system but using UnityEvent for inspector refs and Action for scripted ones, so my EventSO class had to managed two lists of callbacks hidden behind a custom editor.. this was not ideal at all.. Will give a try of UltEvents !
Okay, while I am generally not a fan of these 'unity-agnostic' videos in MOST cases, this guy is fuckign amazign at that, he actually uses all the good sides of this style (abstract simplicity, not shadowing anything with stupid unity garbage) but without remaining in the 'how tf do i use this in unity' garbage. 9.5/10 (im taking away half a point for keeping me in the state of permanent panic due to my phobia to this channel's avatar ;( )
Last time I visited this topic I ended up using Action without Invoke. Supposedly more performant. You can invoke or execute the action by writing NameOfAction() Is there a reason not to use only Actions? Good video.
EventHandler has some advantages over Action. EventArgs can change its data properties without the event signature changing, so you don't have to go through your code changing all the subscribers. Also, the sender object is pretty handy in some situations. To be fair though, both of these problems can be solved by using a custom struct as the generic Action type.
The only difference between "action()" & "action?.Invoke()" is that the former skips the null check. The latter is just a shorthand for: if(action != null) { action(); } It's an extremely negligible performance difference.
Wanted to ask... You say around 7:00 onward that you can use events to decouple, but from what I understand, subscribing to events is tight coupling because you have to have a reference to the classes anyway? Can you help me understand why this is not considered coupling but, say, static classes are?
The way I use an orchestrator class (the main method in this case) to hook up the events is what makes it decoupled. Those three classes have no idea of one another. You can use scriptable objects to take this a step further, which I'll be covering shortly
The null propagation operator confuses me. I get that it checks in case the object is null but what happens if it is? From what I can Google it would just return null, so wouldn't you get a null exception anyways? What if you're trying to assign a potentially null object? Would that make both objects null?
It depends. If its just a function call which is appended after the null propagation operator, it just ceases to execute the function and skips this line of code if its null. if the return value of the function after the null propagation would be assigned to a variable or be handled in any way, that should consider handling a null as a return value. In the later case you should always append a null-coalescing (??) operator to assign some usefull default value in the case a null would be returned.
Please bear with me since I am new to C# But I am confused when you created an instance(object) by typing "public DoSomething Something;" Isn't this just like declaring a variable, like in "public int x" When you want to create an instance, don't you have to do it in class program and type "var Something = new DoSomething(int num)"
Hi tarodev, could you teach us how to handle the UI with a robust panel manager? All my approaches to try to handle ui in unity end up becoming a mess. I want to show several panels, some of them at the same time, with animations using doTween. I would like to see an intermediate or advanced tutorial. It would be great if you could do it
Having to declare a delegate before actually "creating" a delegate makes it seem like it is common to create multiple delegates of the same type... Why would you do that? That doesn't sound really useful... Can someone enlighten me?
For some reason I can't get these Unity Events to work properly no matter what I do. This video seems to do a great job of explaining this, until you actually try to implement it (as a total noob btw) and some type of error is always being thrown.
@@Tarodev Across it? Lol. Does that mean need to attempt it? True, and your walk troughs are great, but just a little advanced and quick. For me at least. I've only been coding in C# for about 2 years.
Hi .i have a question. In this video ( czcams.com/video/aT2zNLSFQEk/video.html ) when he declare lastMove in if statement i realy dont understand because lastMove has no value and he use it minus with Time.time in condition and then assign it with Time.time . I realy dont understand what is the meaning of lastMove in condition when it has no value. Tnx
You camera preview grabs more attention than the content. Just a thought, may be a small avator or smaller camera preview. Thank you in advance. enjoyed your content.
Why am I understand this now after so much studying?? Damn hell . Bless man
This was definitely the most compact and best explanation of events that I've heard so far.
A delegate is literally a fancy, managed wrapper for a function pointer. You can even obtain a function pointer from native code and marshal it into a C# delegate, then pass that delegate around and call it just like any other delegate. This can also work in reverse. Under the hood, a delegate _is_ a function pointer, it just uses a different declarative syntax and hides the actual address and other complexities from you so it can be used more intuitively.
I manually declare delegates sometimes, but many of the most common signatures you'd want to use already have a predefined version like a delegate void with no parameters or several parameters can be declared with Action and Action and when you want to return stuff there's Func and Func (there's variants with numerous parameters like T1, T2, T3, etc). That covers a _lot_ of delegate usage, and it's hard to think of some it won't cover. So why ever declare your own? Well, for intuitive and expressive naming, of course! It can clearly express your intent as a programmer and also make things a bit more type safe. You may not want to use Action for an event representing two totally different things so no one can confuse the two and create hidden bugs that can be hard to find. If it just uses an Action or Func, you can easily have another programmer mix stuff up and have criss-crossing events creating undesirable or fatal behaviors. But if you have two types of delegate clearly named things like _MenuActionDelegate_ and _KeyInputDelegate_ it gets much harder to confuse those things or use the wrong thing! That's a pretty contrived example, but in a real project you'll see how that makes sense if you think about it ...
So, sometimes, it's actually kind of _smart_ to manually define a custom delegate, even if that signature is already defined by built-in ones like Action or Func. Keep in mind, there's _nothing_ special about Action or Func, they're just common delegate declarations exactly like the ones we declare ourselves. Many people don't know this and think those are some kind of special classes with their own fancy code but they're not. This is literally the definition of Action, as follows:
public delegate void Action(T obj);
That's it! That's the entire definition/implementation of Action, just a common delegate with one generic parameter. Nothing special about it other than what the .NET Framework does beneath the hood with _all_ delegates we declare. Microsoft just included these built-in delegate definitions so we'd all have predefined ones that cover almost all the use cases, so we wouldn't have to waste time or add clutter to code if it didn't make any sense to. If I want to quickly use a delegate in one place in my app and be done with it, I'd hate to have to stop and decide where I should go define a delegate signature and then come back to my method I was working on and use it ... much easier to just use a Func or something as a temporary use delegate. But anytime I'm creating something like a custom event system that's consumed from other classes, I do take the time to define my own custom delegates for the sake of clarity and expressiveness ...
P.S. - As always, enjoyed the video and enjoy throwing in my two cents on these topics. It's refreshing to see someone teaching important C# fundamentals and good practices in the Unity world, as there's so much awfulness out there, haha. I share these videos with junior devs on our team that are curious about the topics and want additional information and they enjoy these too! 🙂
Amazing write up Aaron!
im a bit confused. "So why ever declare your own? for intuitive and expressive naming" couldn't you just use the predefined types but name it something that wouldn't cause confusion?
eg. public event action MenuActionEvent;
i dont see the need to declare your own delegates if the predefined ones fit your need
So many people sound like they're just reading from the docs when teaching something. I'm always amazed at how you DON'T do this, but really deliver the material in an understandable way. Brilliant video.
I've been trying to understand exactly what a delegate is for far longer than I would like to admit.
This clear and concise example at the start of the video just made it straight up obvious.
Thank you!!
This is hands down the BEST video on events/delegates in Unity.
This video (and channel) is an absolute gold mine. I really wish this was explained like this to me earlier, it's so clear now. Thanks for taking the time to put this together, I will recommend this video to any confused beginners I might encounter along my way.
You're more than welcome :)
I love that you used real world practical gaming examples. Sometimes I learn about these new programming concepts but its not clicking why I would use them.
This should have a million views. Your channel is amazing. Thank you so much for everything you are doing and for the quality of your content!
Thank you for the kind words Simon 🙏
Loved that this is one of the first videos about events that the person mentions the downside of events/decoupling, which is lack of clarity, and harder debugging, so it's something to definitely use with caution, especially the "static" version of it, since you now can subscribe from literally any script without even holding a reference to a specific instance. Really nice video!
The addition at the end of the video from the next day is just super useful!👍
I'm not a religious man but, God bless you for this video. Thank you.
Thank you for the blessing. I can feel the warmth of it now (probably the sweltering Australian heat though)
thankyou so much! You are one of the few people on CZcams teaching Unity that I can understand
You've gotta love it when someone Really knows the subject matter, and how to relay it. That was an excellent explanation, thank you. You are a step above the other 'monkeys' :D
Hi thank you for such a clear and whide explanation of the topic! good luck with your future content!
Thank you Taro! You’re the first one I met in 4 years of dev who explained delegates, func, and actions clearly and succinctly
That's high praise 😊 tha ms maarten
Well damn I wish I'd seen this years ago. I know how to use delegates but did not know that simplified way of writing them as Actions and static actions. Thanks!
Your videos are better than Google. Quick, straight to the point with immediate examples. Thanks again!
That's some heavy praise
Of all the videos that discussed Events and delegates, yours is the most clear and concise. Good Job!
2:06 i was waiting for it and i'm very satisfied!💯
There are 2 reasons why I use more rarely (static) events: the subscribing/unsubscribing part and the "voyeur"-ability this functionality gives - everyone can subscribe, also he can subscribe redundantly, but I don't want that! I want to limit access and know exactly who gets triggered and who listens - you clearly state it in the video => REDUCED CLARITY! (bravo for giving Pros and Cons on the concept!!!)
Was just researching how Events work to implement a scoreManager using events. This was really helpful, thank you!
I've used delegates in my game mixed with interfaces to change the functionality depending on interactions. It's been super useful to allow my function to change and be called without me having to worry about what it is actually calling.
love this content, please do a series about SOLID in unity with details, thank you so much for your work
I already knew plenty of things about C#, but i could never wrap my head around how delegates work. Your video made it clear to me.
Also, static events seem really useful for my stuff, and i cant really tell why i havent learned them before.
Thank you! Best wishes!
It’s impressive to see how fast your brain works 👍
I'm developing a small 3D game and your channel helps me a lot!
Great informative video! I was just reviewing events & delegates and this video taught me a few new things.
I wasnt ready for this video when I first started watching but I have recently stated calling Unity Events so now I am able to understand this much better. Honestly your channel is amazing! Your personality is hilarious...love all the zingers!
I love the detail into C# in your videos. They have helped me strengthen my skills as a developer. I don't use Unity but I do use C# with Godot and your videos have helped me immensely. Keep up the great work and thank you for what you do!
You're the guy with the clearest explanation out there, thanks man
Nicely explained. The essentials are here.
Nice video, kinda heavy, lots to absorb, but this has given me a good idea of what delegates, actions, event actions are. Thanks
Special thanks for the beautiful picture, beautiful buttons, beautiful sprites, in total - beatifull visual work in your videos which in no way relate to the topics of your videos, but it's very pleasing to the eye
Probably this video not for beginners and your explanation not the best but doesnt matter, your videos so good
It's like comparing buggy win 10 and mac os with amazing controls
In our workplace, we avoid using UnityEvent.
This is because in the past we would spend hours debugging why Foo() is being triggered randomly only to see that Foo() is in a random UnityEvent in a random animation or prefab.
The problem is that if a function is invoked by a UnityEvent, the stack trace will not say which object is invoking that function. The IDE will also mark the function as "not used" so it shows as greyed out and somewhere down the road, a new programmer works on the project and deletes the function tied to a UnityEvent causing all sorts of bugs.
It's less designer-friendly but having functions be explicitly triggered through code only helps reduce bugs in general.
This has somewhat been alleviated though ever since we all switched to Rider because Rider knows if a function is used in a UnityEvent.
This is a major problem for the entire scriptable object architecture workflow. It's toop hard to keep track of what's triggering what.
I stick with standard functions, too.
your explanation is better than most online courses, keep up your content!
Amazing. Easy and simple resource to learn and understand. As wel, you are fun to watch as you make it interesting with the great humour of yours.
I see some JB Rider shortcuts being used. I'd be interested in a video detailing some of the JB Rider tips as it relates to Unity development.. Maybe you can get them to sponsor the video or something :)
I feel enlightened. Thank you.
I'm literally tearing up right now
Genuinely such a great and informative video, thankyou
You deserve everything
That was very well explained!
Thank you FM my boy
Extremely helpful, thank you!
Really Helpful video, as usual, I recently found the 2048 and grid game video. Ngl those types of videos are really great for learning. I found it very helpful. Learned a lot, Thank you!!. Hope you make long videos like those covering a variety of topics.
One thing I like about Actions is that you don't need a definition like Delegates, just the signature.
A good tip is that if you are going to create some kind of custom "EventArgs" to send a group of data, prefer to use struct unless a class is necessary, that will generate less garbage. (that is the struct's function anyway 😁)
Thanks. I took a lot out of that.
Awesome explanation!
Impressive tutorial. Thank you for taking the effort to teach us these topics 😊
I'm glad you enjoyed :)
Nice video and nice information regarding's this topics. I will have to work with them in order to understand them better but now at least I have a general understanding of them so thank you for this video :)
As soon as you added static to the Action ... Why not just call the functions directly? Using the Action made it more complicated and confusing.
Very useful information, thank you.
great teaching skills
Very good video, thanks!
Your videos are great, and very useful. Thank you
Shortest explanation about differences between delegates and events:
An Event is a delegate with 2 restrictions:
1- You can not invoke the delegate reference directly
2- You can not assign to it directly
A bit longer(but sweet and funny)explanation:
czcams.com/video/NgrnCMaxIXM/video.htmlfeature=shared
Dude, you create insanely useful, extremely well explained videos! I like your short on-spot examples to demonstrate everything. Keep up the good work! I hope you make a cooperative video with Jason Weimann and Codemonkey, so your channel gains more popularity. In my opinion you beat both of them: Jason sometimes drifts away from the topic and Codemonkey's tutorials gotta always get paused to check what he speedtyped and moved off screen immediately after that.
Thank you for the kind words 🙏
Hmm... I might watch 300 tonight
@@Tarodev :D just don't watch the sequel. I am being honest with you, watching constantly tutorials for a decade (since Brackeys entered and basically (re)defined the gamedev youtube tutorial scene) in case there is something new in Unity that I missed. You are really good at explaining. Fact.
I try to keep the visualization / UI totally decoupled from game logic and Events (or UnityEvent more specifically) provide a good one-way communication between them. Though sometimes I run into a problem when subscribing and invoking happen in the same frame (new instantiated class subscribes to an event which invokes during the same frame - thus not triggering whatever function I wanted). Thanks for the video anyway! I've always found delegates to be hard to understand.
@12:30 About unsubscribing; Normally I subscribe and unsubscribe exactly like you suggest here (@13:12). But in rare occasions, I found myself having to subscribe to events from multiple locations in my codes. This easily lead to accidental subscriptions to the same event multiple times, which results in it being fired multiple times with each call.
In situations like this, it is possible to unsubscribe first, and then subscribe in the next line. If you are not already subscribed, nothing happens. If you are, you make sure to only add one listener.
A delegate is a type of method, you can define the structure of a method. Remember, All types exist is tell what the type is, and how to use them.
If you assign empty delegate to your event in declaration like OnNewMemberAdded = delegate(){}; then you won't need to check it for null ever.
Great advice!
thank you !
Saw today that "null propagation operator" was basically copied from Swift, although seems as though it's maybe BETTER in C#. That is handy.
I've recently been programming in swift actually! Not such a bad language.
@@Tarodev Swift 5 is generally nice. It was Swift 1-3 that were horrible basically.
thx 4 vid
This is fantastic! You explain the subject so clearly, it helped me out so much. Do you have any plans to cover Observables in the future? I'm trying to learn it at the moment but there doesn't seem to be many tutorials out there that cover the subject in detail.
Lol, this was just so simple to understand now: "A delegate is just a variable which holds a method instead of data"
Makes you wonder how so many guides over complicate it 🤷
Awesome man
Thanks!
For those who dont understand. Dont worry. Just watch it a 47th time like me. You will get it
Great explanation! I became a huge fan of events since I discovered them, but at a certain point I also became too obsessed. As you say in the end, it's good to decouple things when needed but sometimes it might just make your game architecture overly complicated if you decouple too much.
One question I have is: for objects that are constantly being enabled/disabled I usually subscribe to events on OnEnable and unsubscribe on OnDisable. But what about objects that remain enabled throughout the lifetime of a scene and only get disabled/destroyed when a new one is loaded? I usually subscribe on Awake, in those cases... but should I bother to unsubscribe on OnDestroy anyway?
I'm constantly disabling UI-elements and I have trouble getting events to work properly. I was wondering if instead of disabling/enabling, it was better to make the UI-elements invisible? But you claim here it works if you assign the subscription in the Awake? Do you mean C# or Unity-events, or both?
P.S. If you know any good videos for learning proper UI-programming in Unity please share, I find it somewhat cumbersome or hard to wrap my head around.
Contrary to all the comments, I believe this tutorial works only if you already know events and delegates or at least are familiar with them, so I bit of constructive criticism I believe that it lacks explaining of how it works and why.
Hmm... I disagree. I really don't know how I could break it down any simpler. Open to suggestions though
Was getting worried at the start there ... WTH I'm not using any of that, am I doing it wrong??... then Action ... ahhhh that's the one, ok good !! LOL.
See? Now you know where it started and how it all works 😊
ty sir!
Outstanding video!! Quick question, how is the extension/add-on called at 5:23 ? The one that gives you choices to autocomplete/etc.
Is there an alternative inside visualstudio? Thanks a ton!
great stuff, i just wished there wasnt any background music as it can be hard to hear u some times! :(
thanks for the good stuff
Hey Tarodev, awesome video. I've been working on an Event System in Unity that keeps track of all subscriber to debug them more easily.
I just made a class with an action and a GameObject fields. But do you think the EventHandler could do the same ?
Also I'm looking for a way to serialize them in the inspector (just like UnityEvents), have you any take on this ?
I could just use UnityEvent from the start but runtime added callbacks are not serialized so that ruins the purpose.
I tried a custom editor to get the data through reflexion but it's very hard to get the invocation list to show in the inspector in a good way..
To serialize standard delegates in the editor you'll nerd a third part library. Odin does it, but a package called UltEvents does it significantly better
@@Tarodev And it is even free, wow ! Thanks for the reply !
I used the Odin serialization and managed to have a working system but using UnityEvent for inspector refs and Action for scripted ones, so my EventSO class had to managed two lists of callbacks hidden behind a custom editor.. this was not ideal at all.. Will give a try of UltEvents !
I’m gonna look it up, but one of my questions was difference between an Action and UnityAction?
Okay, while I am generally not a fan of these 'unity-agnostic' videos in MOST cases, this guy is fuckign amazign at that, he actually uses all the good sides of this style (abstract simplicity, not shadowing anything with stupid unity garbage) but without remaining in the 'how tf do i use this in unity' garbage. 9.5/10 (im taking away half a point for keeping me in the state of permanent panic due to my phobia to this channel's avatar ;( )
Last time I visited this topic I ended up using Action without Invoke.
Supposedly more performant. You can invoke or execute the action by writing NameOfAction()
Is there a reason not to use only Actions?
Good video.
EventHandler has some advantages over Action. EventArgs can change its data properties without the event signature changing, so you don't have to go through your code changing all the subscribers. Also, the sender object is pretty handy in some situations. To be fair though, both of these problems can be solved by using a custom struct as the generic Action type.
The only difference between "action()" & "action?.Invoke()" is that the former skips the null check.
The latter is just a shorthand for:
if(action != null)
{
action();
}
It's an extremely negligible performance difference.
@@Dxpress_ I completely missread his question
@@Tarodev ¯\_(ツ)_/¯
Wanted to ask... You say around 7:00 onward that you can use events to decouple, but from what I understand, subscribing to events is tight coupling because you have to have a reference to the classes anyway? Can you help me understand why this is not considered coupling but, say, static classes are?
The way I use an orchestrator class (the main method in this case) to hook up the events is what makes it decoupled. Those three classes have no idea of one another.
You can use scriptable objects to take this a step further, which I'll be covering shortly
nice video
The null propagation operator confuses me. I get that it checks in case the object is null but what happens if it is? From what I can Google it would just return null, so wouldn't you get a null exception anyways? What if you're trying to assign a potentially null object? Would that make both objects null?
It depends. If its just a function call which is appended after the null propagation operator, it just ceases to execute the function and skips this line of code if its null. if the return value of the function after the null propagation would be assigned to a variable or be handled in any way, that should consider handling a null as a return value.
In the later case you should always append a null-coalescing (??) operator to assign some usefull default value in the case a null would be returned.
Please bear with me since I am new to C#
But I am confused when you created an instance(object) by typing "public DoSomething Something;"
Isn't this just like declaring a variable, like in "public int x"
When you want to create an instance, don't you have to do it in class program and type "var Something = new DoSomething(int num)"
Not only did you explain delegates and events in the usual C# but also in unity
yoooooooooouuuuuuuuu areeeeee theeeeee best
Thanks honey 🍯
Hi tarodev, could you teach us how to handle the UI with a robust panel manager? All my approaches to try to handle ui in unity end up becoming a mess. I want to show several panels, some of them at the same time, with animations using doTween. I would like to see an intermediate or advanced tutorial. It would be great if you could do it
Having to declare a delegate before actually "creating" a delegate makes it seem like it is common to create multiple delegates of the same type... Why would you do that? That doesn't sound really useful... Can someone enlighten me?
Okay, but what is a difference between a public Action and a public event Action? Didn't catch that bit and thats kinda what I came here for mostly xd
Oh, he just says it much later than I would expect and i was sure i already missed it. okaaay
Hello, what is the font name you use for the video thumbnail? Thank you!
For some reason I can't get these Unity Events to work properly no matter what I do. This video seems to do a great job of explaining this, until you actually try to implement it (as a total noob btw) and some type of error is always being thrown.
Never thought I'd hear someone describe a button as promiscuous, but here we are.
😂
Nah, the difference between an action and a func is how jazzy it gets.
Lol
You are so funny!
Why not just call functions instead of adding it to a delegate?
Is an Action a delegate?
✨
It is 16 arguments because they actually used a Tuple
I just found out about this guy. I didn't know you basically had to know C# down pat to watch his videos lol. He's going way too fast for me.
To be fair, it's a complex topic, and you don't really need to be across it as a beginner. Thanks for watching though :)
@@Tarodev Across it? Lol. Does that mean need to attempt it? True, and your walk troughs are great, but just a little advanced and quick. For me at least. I've only been coding in C# for about 2 years.
Hi .i have a question. In this video ( czcams.com/video/aT2zNLSFQEk/video.html ) when he declare lastMove in if statement i realy dont understand because lastMove has no value and he use it minus with Time.time in condition and then assign it with Time.time . I realy dont understand what is the meaning of lastMove in condition when it has no value.
Tnx
watched the whole video, still no idea how an event works
You camera preview grabs more attention than the content. Just a thought, may be a small avator or smaller camera preview. Thank you in advance. enjoyed your content.