UnityEvents Explained in 4 Minutes

  Рет қаралды 49,063

Contraband

Contraband

Күн бұрын

Пікірлер: 90
@ahand4824
@ahand4824 Жыл бұрын
Can you explain the way to make UnityEvent that can pass some parameters?
@contraband.software
@contraband.software Жыл бұрын
Yes of course: UnityEvents allow up to 4 parameters and you would make them like so: public class TestEvent : UnityEvent { } public TestEvent testEvent; If you wanted to use more parameters or more custom data, you could make a struct like so: public struct TestEventData { float someFloat; PlayerController playerController; int int1; int int2; int int3; } And then define the event like this: public class TestEvent : UnityEvent { } public TestEvent testEvent; If you feel like you want to be more custom/controlled, you can always use normal c# events, however I haven't needed to use them yet.
@ahand4824
@ahand4824 Жыл бұрын
@@contraband.software yeah, I've tried that before, I just wonder if we can store some parameter values (something like serialized enum or object) into scene's gameobject's component from editor window, so we can avoid the use of hard-code.
@contraband.software
@contraband.software Жыл бұрын
@@ahand4824 Yeah about serialization I'm not sure unfortunately
@nuggetschannelcz
@nuggetschannelcz 11 ай бұрын
Try action events,
@JD-ue1do
@JD-ue1do Жыл бұрын
Where were you like 4 years ago when my procrastinating studentass needed this information :( Great video btw, well explained and to the point
@pinkaltercation
@pinkaltercation Ай бұрын
labelling high coupling and decoupling as cringe and pog really helped me wrap my head around this, thanks!
@contraband.software
@contraband.software Ай бұрын
no problem! 😂
@crazyboy2278
@crazyboy2278 Жыл бұрын
Very helpful, informative, and straight to the point and also easy to follow along. Overall great video.
@contraband.software
@contraband.software Жыл бұрын
Thank you!
@ConstantineSakalis
@ConstantineSakalis 20 күн бұрын
Very helpful! I burst out laughing when I heard the FNAF anxiety SFX on NullReference exception
@diothil2920
@diothil2920 6 ай бұрын
This is really nice. It shows a simple way to use it and is a good introduction into eventsystems. I personally never really looked into it, but damn this is useful. (I made myself watch it, because I wanted to learn something new)
@ksualboy9133
@ksualboy9133 Жыл бұрын
Fast, precise and with a little bit of comedy 👌 Loved it.
@contraband.software
@contraband.software Жыл бұрын
Thank you very much:)
@K0BRAKID
@K0BRAKID 6 ай бұрын
Kind of fast paced but I loved how straight to the point it was. thanks!
@solveit1304
@solveit1304 Жыл бұрын
Absolute legend. I faced the same issue. Great video!
@dnl-9235
@dnl-9235 Жыл бұрын
Thanks! very informative and concise
@contraband.software
@contraband.software Жыл бұрын
I'm glad you enjoyed
@z0OZ00OOO
@z0OZ00OOO 3 ай бұрын
Hey this video was awesome, please make more 🙏
@Future_Guy
@Future_Guy Жыл бұрын
I like the pacing of the video. It's very snappy. The content quality however can be improved a bit -- 1) Inside the UIManager, you serialize scoreText but you use FindGameObjectWithTag for the GameController? I feel you could've serialized that. Since it's a single scene and "Find..X" methods are always nasty cuz of strings. 2) It's always good practice to unsubscribe the events before you destroy the object (or during). I think it's important to maintain code quality and reduce code smell right from the start as a lot of beginners end up watching such tutorials. I like the editing in this video. Good luck with the next one! :)
@contraband.software
@contraband.software Жыл бұрын
Thanks! About the first thing, I'm doing FindObject because in practice a lot of objects will have a reference to the game controller (and I mean a LOT) and so it would be awful to have so many manually set references. I'm going to show how using singletons will help a lot in a situation like this in an upcoming video. Plus in reality using findobjectwithtag isnt all that bad as people think, as doing it by tag is much faster and sure you can get the string wrong but that's the only major downside. For the second thing, I actually didnt know about that, that's good to know. What benefits are there to doing that?
@Ymirheim
@Ymirheim Жыл бұрын
​@@contraband.software There is a solution that solves the concerns both of you have. Serialize the field and set it in OnValidate. You get the benefit of both not having to set it manually AND the FindMethod not being called at runtime. [SerializeField] GameController gameController; void OnValidate() { if(!gameController) gameController = FindObjectWithWhicheverMethodIsMostConvenient(); }
@maxboyaditya3857
@maxboyaditya3857 Жыл бұрын
Simple but Gorgeous!!
@zanagi
@zanagi 6 ай бұрын
this is really good. Now I'm wondering if events and UnityEvents are the similar cause I'm trying to do it without assigning stuff to the editor
@elian_geser
@elian_geser 20 күн бұрын
Nice and precise. Tough to see the square shape being abused as a coin when there is a circle also right below :3 but otherwise very nice video. Thank you :)
@thebestcelep6358
@thebestcelep6358 Жыл бұрын
Brilliant and fun video Thanks !
@random_precision_software
@random_precision_software Жыл бұрын
Unity 2022 has new features in, like the procedural clouds and built in water.. I'd like to see tutorials on those and HDRP decals being used in a script !
@contraband.software
@contraband.software Жыл бұрын
Haha I'd have to look into those because that's something I havent heard of before! Sounds really cool though!
@random_precision_software
@random_precision_software Жыл бұрын
Just found your channel, I've subbed and want to see more videos ! !
@contraband.software
@contraband.software Жыл бұрын
Thanks man I appreciate that! I'll be posting soon, just been busy with Uni 😭
@fulgencejuniorlohore854
@fulgencejuniorlohore854 3 ай бұрын
Thanks buddy!
@Wasabiofip
@Wasabiofip Ай бұрын
Good overview, although I think the final part of the example defeats the purpose. I thought the whole point of an event system is that the producers don't need to know about the subscribers? This is what makes it more scalable and de-coupled. Otherwise the producers could directly invoke some method of the subscriber when the event conditions are met. The final example would be improved if the subscriber therefore is the one adding itself: Conceptually it knows it needs to subscribe to the coin collect event, regardless of who is producing the event, and the coins know they need to produce the event, regardless of who is subscribing to it.
@tomasmolina9840
@tomasmolina9840 7 ай бұрын
What’s the point of the Unity Event if you’re still holding direct references to both GameObjects? This doesn’t make the code more modular, at this point just call both functions instead of calling the Unity Event
@contraband.software
@contraband.software 6 ай бұрын
You'll only need the reference once, and the event acts as a middleman that other systems can hook into, rather than the other way around.
@RamonAlonsoLopezMartinez
@RamonAlonsoLopezMartinez 3 ай бұрын
Exactly.
@PharanDev
@PharanDev Жыл бұрын
I think there's a common misunderstanding about how UnityEvents are related to events. They really should've thought of a different name for it than Unity"Event". Events are used for callbacks. The class that wants a callback needs to know about the class providing it. Yes, UnityEvents can be used in a similar way to C# events. But if you just needed C# events, it's a good idea to use C# events. UnityEvents, as we usually use them, are just serialized method calls. So... 1. the dependency is in the opposite direction as a normal event. Even if it's just at the inspector level, the caller implements functionality based on the specific class and method it calls, instead of just accepting any class that asks for a callback. So swapping out a class for testing, or a better implementation in the future, requires you to change 2 things, instead of just 1 thing, even if one of those things isn't in code. This is still coupling but just a different kind, with similar problems as the setup gets more complicated. 2. the dependency is on the Unity object, but not in the code. It will generate errors and break when you change your class/method names. It won't be included with IDE-assisted renaming. The other way to look at it is that it's just Unity doing dependency injection. So just from the .cs files, neither class actually knows about the other. But things can still break based on your inspector settings when either one changes. 3. the logic is defined in the Unity object, so programming and reprogramming is done in the Unity Inspector. This means logic can be determined/designed/changed by people who aren't supposed to touch the code, which can be more efficient or more dangerous based on certain team and project arrangements. If you're an individual developer, it shifts the balance of where you need to look for and fix bugs. You will always need to check both the Unity object setup and the code, but UnityEvents means you have to reason some more things out in the Inspector, which some developers are less comfortable with. 4. UnityEvents help you make the component more general-purpose and reuse it for different things. Like in your example, if Coin.cs was just a receiver for an OnTriggerEnter2D message that invokes a UnityEvent, the component class may as well be called something like "TriggerEnter2DUnityEvent". And it can be reused over and over on different objects in different ways based on what methods you define in the event in the inspector. If you needed specific cases, you can add a separate class (that can be the actual Coin.cs class that does coin-specific things) that the TriggerEnter2DUnityEvent can hook into by setting it up to make calls to specific Coin methods. You can do that with all sorts of things. Like a component that just invokes a UnityEvent when a button is pressed. Both the button and the method call can be set up in the inspector, and the class with the system-specific functionality being called doesn't need to be polluted with input logic. You could also make a component that repeatedly calls a method at a set interval. The amount of time and the method call can be set up in the inspector.
@contraband.software
@contraband.software Жыл бұрын
You raise a lot of good points, I think my favourite is the OnTriggerEnter2DUnityEvent class idea, which in this case would be great, for example I could attach it to a floor area to trigger a lighting effect but also collecting a coin. I also agree about the callbacks stuff, however we have been using UnityEvents to make callbacks and it's been working fine, and personally we find it to be cleaner than standard events and more readable when we are working together on code. We personally find serialisation a massive benefit, and I think you exaggerate the negativity around a longer setup and maintenance whereas for us the positives outweigh the cons. This however I understand can completely be up to the work and team. All in all I stand by that UnityEvents are great for beginners especially, however I will be making a video on C# events and delegates and proper callbacks at some point, and I will take your feedback into account as I think it's very valid and important, and I'm glad you just didnt say "but C# event faster (still valid)" and gave a pretty unique perspective
@PharanDev
@PharanDev Жыл бұрын
@@contraband.software Nah, I wasn't saying setup or maintenance was a huge negative. It's just something you watch out for because it's a different source of bugs. And there are ways to misuse it that yeah it becomes cumbersome compared to a different way of doing things. But if they were useless, you'd get a lot of devs universally hating on them. But I haven't seen experienced devs say that. I guess I failed to bring up a proper point I do think is true. Most of the time, it's not UnityEvents vs C# events. Because they are different tools for different purposes. UnityEvents are good for allowing you to use the inspector to serialize function calls. They're like the simplest form of editor-side visual scripting. They also make the components more general-purpose. That's their strength, and you only need to keep its gotchas in mind if you want to use it with less problems. If later on you feel like you need to write a specific component for a specific thing, you could totally decide do that when it makes sense. C# events and delegates are good for the same things they're good for in other applications, getting parameterized callbacks from code. Put them in processes that take several frames to finish, maybe even give you data back. You can put them in coroutines to get data or timing from it, or allow coroutines to have generalized functionality. You can put them in runtime ScriptableObjects to get notified of changes in systems. They're nice for making dependency of two separate but related systems one-directional. Use them to hook your custom animation system to the player logic because when you have SO MANY events, your inspector would become ridiculously unwieldy. It wouldn't even be possible to use UnityEvents for some cases because some uses require complicated parameters and returns which they simply don't support. So I'd advise anyone against thinking of UnityEvents as kiddy toys VS C# events as professional tools. That's just weird programmer snobbery, the kind of snobbery that experienced devs understand makes no sense. They're just different tools for different purposes. Just agree on how the team should work, and use the right tools to help everyone properly do their job. The wrong tool is the one you'll start having to wrestle with with because it wasn't meant to do what you wanted.
@contraband.software
@contraband.software Жыл бұрын
@@PharanDev I didnt mention it in this video as I didnt want to go into that level of detail, but with unityevents can totally be used as parametetized callbacks, you just create the event as a new class inheriting from UnityEvent Like this I think: public class ParamEvent : UnityEvent I agree that they are different tools for different things in a broader sense, but UnityEvents are still an easier alternative to get a hang of for beginners as C# events are objectively harder to manage to start out with.
Жыл бұрын
Thanks! Your first two videos look good, so i subscribed. Now a question. What is the advantage of using Unity events instead of plain C# events in a case, when you don't add callbacks in inspector but in code?
@contraband.software
@contraband.software Жыл бұрын
Thank you so much! UnityEvents create less memory garbage than standard C# events, however are roughly 2 times slower in terms of speed. The main advantage of UnityEvents is of course the ability to serialize, however another advantage is that they are simply harder to get wrong than C# events, and usually produce cleaner code. It's a matter of preference really since both are already highly optimised :)
Жыл бұрын
@@contraband.software Thanks for answer.
@nil7444
@nil7444 Жыл бұрын
Awesome video!
@contraband.software
@contraband.software Жыл бұрын
Thank you!
@phucminh7713
@phucminh7713 9 ай бұрын
this help a lot, tks sir
@hoody4289
@hoody4289 Жыл бұрын
Hello, nice video, I like the visuals. I would have a suggestion, like using a Singleton instead of using "FindGameObjectWithTag("tagName"), since it's really not efficient (the more objects, the more time it takes) and can lead to issues if you have multiple gameobject using the same tag
@contraband.software
@contraband.software Жыл бұрын
Funny you say that, that's exactly what the next video will be ;) In general Ill also be discouraging finding objects moving forward, as in my own code I'll only find objects once per run and cache results.
@magickomchanell4556
@magickomchanell4556 Ай бұрын
best!!!
@yasin_ozbek
@yasin_ozbek 9 ай бұрын
thanks man
@jaopreto-wlock
@jaopreto-wlock 11 ай бұрын
i loved the FNAF sound at 0:19 hahahah
@attenonmj3708
@attenonmj3708 5 ай бұрын
I am really confused on the part where he made the coin a square and not a circle.
@kr1s85
@kr1s85 10 ай бұрын
Nice Video, nice pace! From a dev point of view, I don't like that the Coin adds the listner. The coin (publisher) should not know about its subsriber.
@contraband.software
@contraband.software 9 ай бұрын
I absolutely agree with you, the way I would actually redo it is have some sort of middleman
@TheGrnx
@TheGrnx Жыл бұрын
trop cool merci
@contraband.software
@contraband.software Жыл бұрын
Merci beaucoup mon ami:)
@karthiknallan559
@karthiknallan559 Жыл бұрын
pog video
@daniionas2888
@daniionas2888 Жыл бұрын
Awesome
@contraband.software
@contraband.software Жыл бұрын
Thank you!
@chkibriamiranmasood9382
@chkibriamiranmasood9382 11 ай бұрын
the best
@lordforlorn5694
@lordforlorn5694 5 ай бұрын
On 3:57, why would I add those methods to an event and then invoke it if I can just execute those methods straight away?
@anshulsingh8326
@anshulsingh8326 7 ай бұрын
Is destroying the best method for endless runner? I heard it's better to use object pooling but offcourse I'm noob and whatever object pooling means I don't know that
@contraband.software
@contraband.software 7 ай бұрын
Destroying an object causes garbage collection which can be bad for performance, so I would absolutely look into object pooling as soon as possible :) Object pooling entails instantiating a bunch of objects at the beginning, then using that pool of objects throughout the runtime of your game, enabling and disabling them for example instead of creating and destroying.
@diothil2920
@diothil2920 6 ай бұрын
@@contraband.software Also this "Object pooling" is a very interesting and (I can imagine) really good idea
@wikileakop8469
@wikileakop8469 Жыл бұрын
good short video!
@contraband.software
@contraband.software Жыл бұрын
Thank you!
@8cto289
@8cto289 Жыл бұрын
Does each instance of the coins make its own event or are events static and shared between every coin? If not, can you make the events static to save on space?
@contraband.software
@contraband.software Жыл бұрын
Yeah so in this video each coin will have its own coin collect event, however you can totally have just one event which coins invoke upon collision! I do something like this in my singletons video: kzbin.info/www/bejne/o3-mo3lsr8iena8
@JimJimJimJimPim
@JimJimJimJimPim Жыл бұрын
Running into an issue, following up to 3:30 - when I try to collect a coin, the game stops and I get an error message: "NullReferenceException: Object reference not set to an instance of an object. UICoontroller.UpdateScore () (at Assets/Scripts/Managers/UIController:cs19). Im wondering if this has anything to do with the text itself, using Text under Legacy perhaps Any help would be appreciated
@contraband.software
@contraband.software Жыл бұрын
Hi sorry for the late reply! If its to do with UpdateScore() method, its most likely that you havent set a reference to a text object to display the score, or the reference is being lost. You shouldnt get a null reference even if you havent set a listener so I think it might be a missing component. Another thing is that I used TextMeshProUGUI, not the legacy text, so make sure youve got a reference to the correct component type. Let me know if this helped. Also, do you think it would be beneficial if there was like a public discord channel where you could send me pictures etc, because if so I might set one up for the future
@SLthenus
@SLthenus Жыл бұрын
this is only work for object that always together in every scene. If player change scene, the reference will lost
@contraband.software
@contraband.software Жыл бұрын
Obviously, because when the instance that has subscribed to an event gets destroyed the reference is lost. However, if the event itself survives a scene change (say because it's a singleton), firing that event wont cause any errors.
@yavuzyagmuryank5675
@yavuzyagmuryank5675 Жыл бұрын
So what if we need to enter parameter on our methods? i want to use unityevent like IncrementScore(10) from Coin script but it looks like its not possible.
@contraband.software
@contraband.software Жыл бұрын
UnityEvents allow up to 4 parameters and you would make them like so: public class TestEvent : UnityEvent { } public TestEvent testEvent; If you wanted to use more parameters or more custom data, you could make a struct like so: public struct TestEventData { float someFloat; PlayerController playerController; int int1; int int2; int int3; } And then define the event like this: public class TestEvent : UnityEvent { } public TestEvent testEvent; If you feel like you want to be more custom/controlled, you can always use normal c# events, however I haven't needed to use them yet.
@yavuzyagmuryank5675
@yavuzyagmuryank5675 Жыл бұрын
@@contraband.software thanks a lot
@yavuzyagmuryank5675
@yavuzyagmuryank5675 Жыл бұрын
@@contraband.software it was really helpfull
@damislav
@damislav Жыл бұрын
Pog video
@contraband.software
@contraband.software Жыл бұрын
Thank you sirrrrr😎
@dixiem2139
@dixiem2139 Жыл бұрын
why my score doubles? ._. it becomes 2 per coin
@contraband.software
@contraband.software Жыл бұрын
You may be invoking the event twice per coin but im not too sure without seeing any code
@realElzie
@realElzie 10 ай бұрын
So from my understanding... its just bluetooth method calling lol
@contraband.software
@contraband.software 9 ай бұрын
yeah i guess? XD
@jakubsluka4168
@jakubsluka4168 Жыл бұрын
this video takes 4 minutes only bcs its fast as heck which is stupidly hard to follow.
@jakubsluka4168
@jakubsluka4168 Жыл бұрын
I needed to implement event in a bit different and more complex scenario a and i was a bit angry bcs i could get the basics.. Well I managed to did it using this video after all. Thanks
@NoTalkingHere-oj3bm
@NoTalkingHere-oj3bm Жыл бұрын
bad video
@contraband.software
@contraband.software Жыл бұрын
Let me know what makes it bad, any feedback is helpful :)
@NoTalkingHere-oj3bm
@NoTalkingHere-oj3bm Жыл бұрын
@@contraband.software it was to complicated for a simple beginner like me and i don't think you explained some of the concepts well (for me at least)
@NoTalkingHere-oj3bm
@NoTalkingHere-oj3bm Жыл бұрын
@@contraband.software i think it was because you were trying to explain it in 4 minutes
@contraband.software
@contraband.software Жыл бұрын
@@NoTalkingHere-oj3bm thank you for the feedback, in my next video I'll try go a bit slower :)
@melamri6640
@melamri6640 Жыл бұрын
Question to make the event happen you do coinCollect.Invoke() I thought that Invokes were supposed to make something wait? in this context what does it mean or am I just understanding them wrong?
Events & Delegates in Unity
13:20
Game Dev Beginner
Рет қаралды 58 М.
Better Coding in Unity With Just a Few Lines of Code
15:27
Firemind
Рет қаралды 311 М.
Incredible: Teacher builds airplane to teach kids behavior! #shorts
00:32
Fabiosa Stories
Рет қаралды 12 МЛН
Building Runtime UI with UI Toolkit In Unity
21:35
Game Dev Guide
Рет қаралды 45 М.
What are Events? (C# Basics)
15:05
Code Monkey
Рет қаралды 393 М.
⚡ Всё про события в Unity 3D
21:38
Emerald Powder
Рет қаралды 106 М.
Why I Started Game Dev In My Late 30s
7:32
Game Dev With Michael
Рет қаралды 23 М.
How to Program in Unity: Observer Pattern Explained
15:57
iHeartGameDev
Рет қаралды 114 М.
Events or UnityEvents?????????
15:43
Jason Weimann (GameDev)
Рет қаралды 104 М.
20 Advanced Coding Tips For Big Unity Projects
22:23
Tesseract
Рет қаралды 187 М.
C# Events & Delegates
17:21
Tarodev
Рет қаралды 88 М.
Delegates, Events, Actions and Funcs - The Observer Pattern (Unity & C#)
11:48