UnityEvents Explained in 4 Minutes

Поділитися
Вставка
  • Опубліковано 26 чер 2024
  • In this video you'll learn about what Events are, why you should use them, and how to use them in Unity. This video is valid as of 2023. This video will only cover UnityEvents and not C# events and delegates, as I think UnityEvents are more beginner friendly (Personally I have been only using them for like 2 months lol).
    FOLLOW THE SOCIALS:
    Instagram: / contraband.software
    TikTok: / contraband.software
    MUSIC:
    Journey's End by Purrple Cat
    TIMESTAMPS:
    00:00 - Intro
    00:04 - What are Events?
    00:13 - Why should we use them?
    00:51 - Setup
    01:26 - Subsciber methods
    02:35 - Creating a UnityEvent
    03:05 - Adding Listeners
    04:16 - Demo
    04:24 - Outro

КОМЕНТАРІ • 84

  • @ahand4824
    @ahand4824 Рік тому +11

    Can you explain the way to make UnityEvent that can pass some parameters?

    • @contraband.software
      @contraband.software  Рік тому +8

      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 8 місяців тому

      Try action events,

  • @JD-ue1do
    @JD-ue1do Рік тому +10

    Where were you like 4 years ago when my procrastinating studentass needed this information :( Great video btw, well explained and to the point

  • @solveit1304
    @solveit1304 8 місяців тому +2

    Absolute legend. I faced the same issue. Great video!

  • @crazyboy2278
    @crazyboy2278 Рік тому +8

    Very helpful, informative, and straight to the point and also easy to follow along. Overall great video.

  • @thebestcelep6358
    @thebestcelep6358 11 місяців тому

    Brilliant and fun video Thanks !

  • @z0OZ00OOO
    @z0OZ00OOO 11 днів тому

    Hey this video was awesome, please make more 🙏

  • @ksualboy9133
    @ksualboy9133 Рік тому +2

    Fast, precise and with a little bit of comedy 👌 Loved it.

  • @diothil2920
    @diothil2920 2 місяці тому +1

    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)

  • @dnl-9235
    @dnl-9235 Рік тому +1

    Thanks! very informative and concise

  • @K0BRAKID
    @K0BRAKID 3 місяці тому

    Kind of fast paced but I loved how straight to the point it was. thanks!

  • @maxboyaditya3857
    @maxboyaditya3857 Рік тому +1

    Simple but Gorgeous!!

  • @fulgencejuniorlohore854
    @fulgencejuniorlohore854 5 днів тому

    Thanks buddy!

  • @nil7444
    @nil7444 Рік тому

    Awesome video!

  • @phucminh7713
    @phucminh7713 6 місяців тому

    this help a lot, tks sir

  • @yasin_ozbek
    @yasin_ozbek 6 місяців тому

    thanks man

  • @random_precision_software
    @random_precision_software Рік тому +1

    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 😭

  • @daniionas2888
    @daniionas2888 Рік тому

    Awesome

  •  Рік тому +4

    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  Рік тому +5

      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 :)

    •  Рік тому +2

      @@contraband.software Thanks for answer.

  • @zanagi
    @zanagi 2 місяці тому +1

    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

  • @chkibriamiranmasood9382
    @chkibriamiranmasood9382 7 місяців тому

    the best

  • @TheGrnx
    @TheGrnx Рік тому +1

    trop cool merci

  • @Future_Guy
    @Future_Guy Рік тому +9

    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  Рік тому +2

      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 Рік тому +2

      ​@@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();
      }

  • @marcusviniciussilvaoliveir8559
    @marcusviniciussilvaoliveir8559 7 місяців тому +1

    i loved the FNAF sound at 0:19 hahahah

  • @karthiknallan559
    @karthiknallan559 Рік тому +1

    pog video

  • @random_precision_software
    @random_precision_software Рік тому +2

    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  Рік тому +1

      Haha I'd have to look into those because that's something I havent heard of before! Sounds really cool though!

  • @lordforlorn5694
    @lordforlorn5694 2 місяці тому

    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?

  • @hoody4289
    @hoody4289 Рік тому +1

    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  Рік тому +2

      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.

  • @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

  • @8cto289
    @8cto289 11 місяців тому

    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  11 місяців тому

      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:
      ua-cam.com/video/mNCrF6zckgM/v-deo.html

  • @wikileakop8469
    @wikileakop8469 Рік тому

    good short video!

  • @tomasmolina9840
    @tomasmolina9840 3 місяці тому +3

    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  3 місяці тому +2

      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 16 днів тому +1

      Exactly.

  • @attenonmj3708
    @attenonmj3708 Місяць тому +1

    I am really confused on the part where he made the coin a square and not a circle.

  • @damislav
    @damislav Рік тому

    Pog video

  • @yavuzyagmuryank5675
    @yavuzyagmuryank5675 11 місяців тому

    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  11 місяців тому +1

      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 11 місяців тому

      @@contraband.software thanks a lot

    • @yavuzyagmuryank5675
      @yavuzyagmuryank5675 11 місяців тому

      @@contraband.software it was really helpfull

  • @PharanDev
    @PharanDev Рік тому +4

    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 Рік тому +1

      @@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.

  • @kr1s85
    @kr1s85 6 місяців тому

    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  5 місяців тому

      I absolutely agree with you, the way I would actually redo it is have some sort of middleman

  • @anshulsingh8326
    @anshulsingh8326 4 місяці тому

    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  4 місяці тому

      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 2 місяці тому

      @@contraband.software Also this "Object pooling" is a very interesting and (I can imagine) really good idea

  • @dixiem2139
    @dixiem2139 Рік тому

    why my score doubles? ._. it becomes 2 per coin

    • @contraband.software
      @contraband.software  Рік тому +2

      You may be invoking the event twice per coin but im not too sure without seeing any code

  • @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.

  • @realElzie
    @realElzie 7 місяців тому

    So from my understanding... its just bluetooth method calling lol

  • @jakubsluka4168
    @jakubsluka4168 10 місяців тому

    this video takes 4 minutes only bcs its fast as heck which is stupidly hard to follow.

    • @jakubsluka4168
      @jakubsluka4168 10 місяців тому

      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?