Object References in Unity - How to Communicate Between Scripts

แชร์
ฝัง
  • เผยแพร่เมื่อ 11 ม.ค. 2022
  • As a new dev, keeping references to game objects you need can be a little confusing. Learn how to store game objects for later use as well as allowing external scripts access to your goodies.
    Instead of trying to find an object, shift your thought pattern a little and ask "should I already know where this object is?".
    ❤️ Become a Tarobro on Patreon: / tarodev
    =========
    🔔 SUBSCRIBE: bit.ly/3eqG1Z6
    🗨️ DISCORD: / discord
    ✅ MORE TUTORIALS: / tarodev
    0:50 - Find Methods
    1:45 - GameObject from Instantiate
    2:33 - Component from Instantiate
    3:49 - Multiple Components
    4:59 - Static Instance
    5:42 - Public Access Modifier
    8:08 - Constructors
    9:20 - MonoBehaviour "Constructor" (Init)
    11:00 - OnCollision
    11:50 - TryGetComponent
    12:41 - GetComponent
    13:03 - SendMessage
    13:35 - Closing

ความคิดเห็น • 318

  • @Tarodev
    @Tarodev  2 ปีที่แล้ว +73

    The "Unit" class is a simple class I created to represent a unit in my game. It's NOT an inbuilt class. Sorry for the confusion

    • @ghostgang4ever
      @ghostgang4ever ปีที่แล้ว +6

      haha thank u bro!! I was googling "unit vs gameObject unity" lol trying to find documentation XD

    • @flyingdutchman2692
      @flyingdutchman2692 ปีที่แล้ว +2

      Big plus for using properties with private setter. I see a bunch of Unity tutorials exposing private field as public, and then argue with: "Everyone knows this should be changed only within it's own class".

    • @vitriolicAmaranth
      @vitriolicAmaranth 8 หลายเดือนก่อน

      That part was honestly very confusing because of that. I had no idea what you were talking about until I scrolled down to make a joke about it and saw this pinned comment.

  • @synchaoz
    @synchaoz 2 ปีที่แล้ว +185

    Intermediate dev here, already doing basically everything you showed but this vid taught me how to do some of those things a little better and smarter. Great stuff.

  • @RobinDoesUnity
    @RobinDoesUnity 2 ปีที่แล้ว +52

    Man, the Instantiate() thing blew my mind. I've been instantiating things as GameObjects and then getting the component for a year now. Glad I clicked on this video and found out there is a shorter path!

  • @gadgetboyplaysmc
    @gadgetboyplaysmc 2 ปีที่แล้ว +11

    I've been watching your tutorials for a few months now and most of these ways, I've actually just picked up from your tutorials alone. Kinda cool how you put them all together here so they're easier to see. You just validated the way I've been doing object references. Thank you!
    I was also always curious why we couldn't use constructors in Unity too, but I guess the Init() thing is the way to go.
    I try to keep my object reference relationships the same way I do with React web dev---hierarchical and mostly self-contained. But I can't avoid those triangular relationships with classes where child classes need to reference their siblings. I mostly try to just move the data I need for two siblings to the parent to keep them self-contained, to keep that hierarchical structure.

  • @calvindebeverly7410
    @calvindebeverly7410 ปีที่แล้ว +2

    Total newbie to Unity, but I understood everything you pointed out in the video, and it answered a vexing question in my mind as to how to reference information from one script to another. Thank you.

  • @mattsponholz8350
    @mattsponholz8350 2 ปีที่แล้ว

    Excellent overview! Love your videos, man. For me this was a good refresher, but I'm positive this stuff is life changing for any newer dev watching. Keep up the great work!

  • @ZacMarvinGameDev
    @ZacMarvinGameDev 2 ปีที่แล้ว

    Did your channel is a GOLD MINE. Every video I watch I learn something new and I’ve been using unity for over 3 years. Thanks so much for all the content!

  • @ZahhibbDev
    @ZahhibbDev 2 ปีที่แล้ว +5

    As usual mate, great work in making things so clear and digestible! Even though I feel decent in my programming experience and knowledge I always learn something new from your videos. :)

  • @KevinTrans
    @KevinTrans 2 ปีที่แล้ว +1

    I have been using Unity for more than one year and never knew about the Instantiate trick, Thanks you !

  • @kingofroms7224
    @kingofroms7224 2 ปีที่แล้ว

    Believe me buddy you are helping us more than 100s of youtubers, they only show how to do stuf, you are showing us how to do stuf in the right way. Plz continue making these type of awesome videos

  • @Warwipf
    @Warwipf 2 ปีที่แล้ว +1

    You're the best Unity channel out there. I feel like some of the other TH-camrs barely know what they are talking about.

  • @oliversdouglas
    @oliversdouglas ปีที่แล้ว +2

    oh my goodness, this video was just what I needed
    that public static Class Instance trick is just beautiful

  • @windwalkerrangerdm
    @windwalkerrangerdm 2 ปีที่แล้ว +3

    Amazing! Besides being old or a new dev, this has to do with being self-thought and being exposed to "harmful" tutorials a lot. THIS IS GOLD AND I LOVE YOU AND YOUR BEARD!

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว

      Thanks for the beard compliment ❤️

  • @lyrion0815
    @lyrion0815 2 ปีที่แล้ว +2

    There is still a better way to expose the Units of the UnitManager to other classes. The way you do it, every other class could still call .Add() or .Clear() on the List since you expose the complete List class. Instead you should:
    private List _units = new List();
    public IReadOnlyList Units => _units;
    This way you can change the _units field only from within the UnitManager, and every other class can only read the units but not change the list at all - thats what the UnitManager is responsible for.
    Great video!

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      Yup, great suggestion. Also you could turn your unit manager into a proper repository and just expose api-like functions.

  • @lunkums
    @lunkums 2 ปีที่แล้ว +5

    this is an incredibly helpful reference especially for beginners!

  • @JBtheWARVillain
    @JBtheWARVillain 2 ปีที่แล้ว

    1 year in, Jnr Game Dev working to Intermediate next 2 months, bit nervous as feels like I've barely scratched the surface. You have so much great insight, such a big help. I look forward to all your vids

  • @machlordundead
    @machlordundead 2 ปีที่แล้ว +1

    ty for all the vids, PLX dont stop doing! i'm learning so much!

  • @amogh2101
    @amogh2101 2 ปีที่แล้ว +1

    Thanks for covering these topics in some of the recent video. It's on point and done well!

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว

      You're welcome Aj

  • @ozcanolguner4947
    @ozcanolguner4947 2 ปีที่แล้ว

    He is really an awesome instructor in all aspects. To-the-point, brief, simple and with high level of knowledge. And I found his jokes fun. Well most of the time:)

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว

      Sometimes my jokes can be a little off-base 😂

  • @luckyknot
    @luckyknot 9 หลายเดือนก่อน +1

    Amazing video about intercom between objects, architecture in Unity is definitely one of the toughest subjects to master and do well, thanks for the explanations!

  • @Tharky
    @Tharky 2 ปีที่แล้ว

    I loved the opening bro, thanks for the video. It's all good information for beginners.

  • @marcinlewandowicz
    @marcinlewandowicz 2 หลายเดือนก่อน

    Awesome stuff man, I really appreciate the quality of your content! :)

  • @larryd9577
    @larryd9577 2 ปีที่แล้ว +1

    Great stuff right here! There are also *events*! They allow us to structure our architectural dependencies without cycles. And you can have information flow in both ways. This can easily be a dedicated video in on itself.

  • @DanPos
    @DanPos 2 ปีที่แล้ว +1

    Great and informative video as usual!

  • @TriCombStudio
    @TriCombStudio 2 ปีที่แล้ว +1

    Thank you, new dev. Super informative. Subbed!

  • @MyLOBsTerr
    @MyLOBsTerr ปีที่แล้ว +1

    Very useful staff! Got some new ideas for my project :) Thanks man

  • @calinzavoi
    @calinzavoi 2 ปีที่แล้ว

    Amazing video! I found it extremely useful and it is even more useful for beginners.

  • @vaulb
    @vaulb ปีที่แล้ว +3

    I don't often write comments, but this video is hidden gem. I have been doing some Udemy game courses and watched countless youtube videos. None of them managed to explain this with same clarity as you. Going a bit fast there, but I slowed down the video and watched it multiple times. Subscribed and checking your other videos now :)

    • @Tarodev
      @Tarodev  ปีที่แล้ว

      Welcome aboard

  • @francescagreetham1804
    @francescagreetham1804 2 ปีที่แล้ว

    New dev here - thank you so much! I was struggling so much to find and decide on a clean way to reference between scripts. So good to hear this advice! Can’t thank you enough!

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      You're welcome. So glad I could help you out 😊

    • @francescagreetham1804
      @francescagreetham1804 2 ปีที่แล้ว +1

      @@Tarodev very excited to work my way through all your videos! 😁

  • @thumbwiz
    @thumbwiz ปีที่แล้ว

    Took me way too long to find this video. Now I need to do some re-writing. Thanks for this awesome video!

  • @Ricochetaglet
    @Ricochetaglet 10 หลายเดือนก่อน

    Tarodev: Making us all better by the video!! 🎉

  • @AndrewNostromo
    @AndrewNostromo 2 ปีที่แล้ว +1

    Great content, keep it coming!

  • @rhyspuddephatt
    @rhyspuddephatt 2 ปีที่แล้ว +16

    UnityEvents are amazing for decoupling components. You can use them to trigger music, animation, partials, other scrips. It means the code you write about health doesn't need to know about who is should tell, it doesn't know about UI or the rest of the world. This works best in prefabs. Suddenly you can have flexible components that you only couple when you make a prefab

    • @monohybridstudios
      @monohybridstudios ปีที่แล้ว +1

      I strongly suggest using System.Action (or delegates if you prefer) instead of UnityEvents. UnityEvents are nice that they can be coupled via the inspector but links can be broken and must be maintained. Whereas, System.Action will be subscribed/unsubscribed at gameObject OnEnable and OnDisable. If you prefer the inspector method, then UnityEvents are quite nice. I'm just of the mind that the less I can couple my references to the inspector then the better.

    • @rhyspuddephatt
      @rhyspuddephatt ปีที่แล้ว

      ​@@monohybridstudios when the functionality I want is inspector hookups is there a good way to do that with delegates, the main usecase I have is prefabs made of generic components that allow for the game designer to have final say. Eg the interaction component could be used in the chest prefab the npc prefab or interact with more global systems like sound or anything else. that the player can walk up to and interact with.
      I will agree they get difficult outside of the prefab space or known static objects made in the inspector but still a very useful tool.
      Further a pure delegate pattern is very helpful in systems that don't touch the inspector

    • @monohybridstudios
      @monohybridstudios ปีที่แล้ว

      @@rhyspuddephatt Gotcha. I agree. UnityEvents are perfect for handing off the a game designer for use in the inspector!

    • @rhyspuddephatt
      @rhyspuddephatt ปีที่แล้ว

      @@monohybridstudios if in doubt make it a designers problem XD in seriousness it's a great way to decouple small behaviour for designers to play with. Making gamejams so much more fun, when the designers gets to play with lego

  • @ikshura
    @ikshura ปีที่แล้ว

    Man I was stuck for 2 days trying to figure out a way to refer a label in my game's main menu UI from a network prefab (Basically making a reference to something upper the hierarchy) and your video saved me. Thank you very much!

  • @skippythemagnificent8103
    @skippythemagnificent8103 2 ปีที่แล้ว

    Really valuable video: at 10:28 I sat jaw opened and swear I heard the lyrics to Windmills of your mind "... like the circles that you find in the windmills of your mind .." : ) many thanks.

  • @SteffDev
    @SteffDev ปีที่แล้ว +1

    Lot's of useful tips , thankyou!

  • @michalbalicky4797
    @michalbalicky4797 2 ปีที่แล้ว +22

    Great stuff. What I have seen so far not only in private projects but even in many Unity tutorials, Unity devs don't know how to structure code, what practices are good or bad or even know base rules of C#.

    • @NukeCloudstalker
      @NukeCloudstalker ปีที่แล้ว

      Not even C# devs do.
      They think abstraction is good, decoupling is a universal boon, and that data and behaviour should go hand in hand.

  • @lechauffagiste2240
    @lechauffagiste2240 2 ปีที่แล้ว +1

    Merci Beaucoup!
    I discovered your channel a few days ago, I'm learning a lot of interesting things. I'm drugged now :). Continue your great job.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว

      All drugged up and feeling good?

    • @lechauffagiste2240
      @lechauffagiste2240 2 ปีที่แล้ว

      @@Tarodev yes everything is fine, just a few hallucinations where I see you in a cat or in a sponge bob

  • @stevancosovic4706
    @stevancosovic4706 ปีที่แล้ว

    Thanks man, great videos!

  • @512Squared
    @512Squared 2 ปีที่แล้ว

    I look forward to the day I would be bored shitless by this kind of video. Until then, I'm just really happy to see someone that is reinforcing the 80% of what you said that I do know and giving a great intro to the 20% that I didn't know (constructors).
    This kind of thing should be Unity 101.

  • @headstart3570
    @headstart3570 ปีที่แล้ว +2

    Really great video, I learnt alot! legend

  • @Sackwiz
    @Sackwiz ปีที่แล้ว

    Excellent video, this is exactly the type of stuff I need! Would love a coaching session perhaps in the future xD

  • @ulricleprovost707
    @ulricleprovost707 2 ปีที่แล้ว +1

    Hey, thanks for thoses really cool tips and example !

  • @paulshepherd300
    @paulshepherd300 2 ปีที่แล้ว

    Great Content !! , thanks for all the Videos :)

  • @Eagle-pe9pg
    @Eagle-pe9pg 2 หลายเดือนก่อน

    Awesome content (AGAIN) thank you!

  • @PixelbugStudio
    @PixelbugStudio 2 ปีที่แล้ว +1

    Great video man.

  • @MIDGETPANCAKES
    @MIDGETPANCAKES 2 ปีที่แล้ว +16

    I love your videos. Would be really helpful to get one talking about different types of event systems. Delegates vs EventHandler vs Action (vs UnityEvents), that sort of thing.

  • @svendpai
    @svendpai 2 ปีที่แล้ว +2

    Thank you taro ❤️

  • @gattra
    @gattra 10 หลายเดือนก่อน +3

    You may not be able to set the Units list when using a private setter, but you can directly manipulate the list itself and since it’s the same reference, you will be modifying the list in the UnitManager. That’s why it’s best to use the readonly keyword or create a copy of the list and return that instead of a direct ref to the list

  • @tobihendrix1324
    @tobihendrix1324 ปีที่แล้ว +7

    Using a reference on each "Unit"-Object might sound good for readability, but if you have a lot of this units you will have an extra 4 Byte / 8 Byte(on x64) memory on each instance just to keep the same reference. I mean today on modern hardware that sounds not so much but it is actually unnecessary space that you are allocating. The singelton implementation just uses this memory once. Not that the way you are doing it is wrong, its acutally a good design in most of the cases. Just wanted to point that out.

  • @kostishkov-log8592
    @kostishkov-log8592 2 ปีที่แล้ว

    Very helpful video, thanks! Watched video about ObjectPool, and tried understand fiches about Init(), and others. I think I got it well, but this video got me all completely understanding)

  • @endorphingames2957
    @endorphingames2957 ปีที่แล้ว

    Love your videos. Get to learn something different about coding in each one

  • @meshavorazoon979
    @meshavorazoon979 2 ปีที่แล้ว +1

    Abyss Watcher Boss art on the wall 😍😍😍

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      One of the most badass bosses of all time

  • @alextheguy4469
    @alextheguy4469 10 หลายเดือนก่อน +1

    This is such important info, thank you. I had to rewatch this a few times but once it clicked, it made my sloppy coding much better (I still suck though)

    • @Tarodev
      @Tarodev  10 หลายเดือนก่อน +1

      Sounds like you're hungry to learn, so keep going and you'll be a pro

    • @alextheguy4469
      @alextheguy4469 10 หลายเดือนก่อน

      @@Tarodev fingers crossed!

  • @otdewiljes
    @otdewiljes ปีที่แล้ว

    Aaaaaah, Unity annexed the C# constructors.
    That explains a lot. Thanks!

  • @ulricleprovost707
    @ulricleprovost707 2 ปีที่แล้ว +67

    Also i'd love to have your input about design patterns in Unity

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +26

      More advanced patterns? If you're after beginner ones I just did a video on a few :)

    • @ulricleprovost707
      @ulricleprovost707 2 ปีที่แล้ว +6

      @@Tarodev like the good pattern to use depending the kind of games, for example i'm doing a tiny 2d drag and drop game. And i'm using singleton there and i don't know if it's good practice here. That's working fine and well in my project, but maybe there is simple ways. I'll look back at your video as well thanks : )

    • @Scorpymhk
      @Scorpymhk 2 ปีที่แล้ว +6

      @@ulricleprovost707 Singleton is a widely used programming pattern. That is to say, singletons are not so specific that they work well for one type of game and not for another. If your game reaches a very high level of size and complexity, you might consider adding a tool for dependency injection, but Singletons will always work.
      Otherwise, there are very few downsides to the singleton which can be summed up as follows:
      - Don't expose public methods or properties on your singleton that let just anyone mutate them. Only expose publicly what is actually needed, and expose it in such a way that another class accessing the singleton can't modify it.
      - Singletons don't work well in the context of unit tests. If you have classes that perform critical or complicated or otherwise error prone business logic enough to warrant unit tests, you should make it so that those classes do not directly rely on singletons.

    • @fmproductions913
      @fmproductions913 2 ปีที่แล้ว +7

      @@ulricleprovost707 The thing with design patterns is that they are like blueprints for solving a specific problem or set of problems. If you get good at identifying your requirements and such, you might get a better feel for choosing the right design pattern. Singleton can be fine, but there are caveats:
      - They introduce dependendencies to other objects which can make it more difficult to do sandbox testing (just throwing enemies into a scene and seeing how they interact with the environment for example - you will always need a valid instance of your singleton in the scene)
      - A more common issue is the reduced testability.
      For tests where you check specific methods or procedures, the non-relevant dependencies are often mocked. Meaning that for dependencies to other classes, you might use an interface that will not call the actual singleton in this case, but a proxy class with empty methods. You can use dependency inversion and singleton pattern together though, so you can have a static method or a library where you request a type instance - an interface that your singleton implements - and that method will resolve it to either the actual singleton implementation or something else.

    • @ulricleprovost707
      @ulricleprovost707 2 ปีที่แล้ว +2

      @@fmproductions913 hey thanks for your awnser and clarification about singletons here ! :)

  • @DavidZobristGames
    @DavidZobristGames 2 ปีที่แล้ว

    Wow wow I am a noob. I did the gameobject storing than grabbing the component / monobehaviour.
    Thanks!
    I did the Init(); thing too, but wasnt sure about it if other devs do this too? So great to see you mentioning this aswell.
    Its great because you can be 100% sure that all required initial processes on the manager are done before calling init() in its targets.

    • @gasparweb
      @gasparweb 2 ปีที่แล้ว

      Yeah! I think it is worth mentioning that you should test if "Init()" was run before other logic. Because after the Instantiate, the Awake and OnEnable method runs on the other monobehaviour...

  • @RealisiticEdgeMod
    @RealisiticEdgeMod 2 ปีที่แล้ว

    Great vid.

  • @pedropc5824
    @pedropc5824 2 ปีที่แล้ว +1

    The man is a genius

  • @windup247
    @windup247 ปีที่แล้ว

    You're my favorite Unity youtuber :D. Do you have any plans to go over Scriptable Objects (e.g. the way introduced in the now famous talk from Ryan Hipple?) I didn't see that topic in your channel, but it seems like either lots of devs like to use them everywhere or barely (if at all.) Either way, keep up the great work, you are amazing at clearing up extremely confusing and complicated topics in C# and Unity!

  • @SweetHoneycode
    @SweetHoneycode 2 ปีที่แล้ว

    Very helpful. Unity Learn touched on this but didn't give this style of example to see how it works.

  • @TheKr0ckeR
    @TheKr0ckeR 2 ปีที่แล้ว

    Tarofangay here. Thanks for the great video! Gonna watch & take notes from everything you mention.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      Enjoy buddy, thanks for the suggestion

    • @TheKr0ckeR
      @TheKr0ckeR 2 ปีที่แล้ว +2

      @@Tarodev This should be most watched beginner Unity & C# video. I mean people are really getting hard times referencing things when not using the methods u mentioned as start. But that's a point-shot!

  • @gamepass505
    @gamepass505 2 ปีที่แล้ว +1

    Thank you!

  • @hossein818
    @hossein818 2 ปีที่แล้ว

    thx. a great tutorial for beginners. There was overcoocked 2 ost background of the tutorial. xD

  • @MandyLeeYT
    @MandyLeeYT 2 ปีที่แล้ว +1

    I like your video, cool thumbnail :)

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว

      Thanks mandy

  • @jarrettonions3392
    @jarrettonions3392 7 หลายเดือนก่อน +1

    Finding game objects and getting components since the journey began 😂

  • @jirikucera9731
    @jirikucera9731 2 ปีที่แล้ว +3

    Hi! Thanks a lot for this video!! There were quite a few things that I didnt know you could do in Unity and some of them are still not quite clear to me. Initially you define a gameObject prefab, reference it by just dragging it into the SerializedField on the script and then play around with it. Later you change that prefab type from gameObject to Unit which is a MonoBehaviour/class that you defined in another script which is sitting attached to your unit prefab gameObject. In order to reference that Unit object rather than the gameObject itself you do the same thing i.e. drag the prefab gameObject into the SerializedField in the inspector. This is where I am confused a bit. Is Unity smart and it finds the Unit object/Monobehaviour attached to your Unit prefab/gameaobject when you drop it there? For instance, if I created an image and then had a script with a public variable Transform imageTransform would I be able to reference that transform by dragging and dropping the whole Image object into the field? Hope this is not too confusing :D. Secondly, you then go on to instantiate that prefab object by calling Instantiate(Unit). I always thought that you need to instantiate by referencing a gameObject but here you reference your custom object Unit. Is Unity smart and it realizes that it needs to Instantiate the object that Unit script is attached to? Would it be possible to instantiate an object by passing in another component of the object to the Instantiate() call? Say its transform, sprite renderer, etc. Thanks so much and apologies for the long question!

  • @rafaelache8650
    @rafaelache8650 2 ปีที่แล้ว

    I loved this

  • @adamolesiak6528
    @adamolesiak6528 2 ปีที่แล้ว +1

    Imo some kind of dependency injection is worth mentioning. Way cleaner than the singleton example, can have different implementations based on build platform or scene that you’re in without polluting the unit manager code or the code of its use cases

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว

      You're right, I wish I added DI to this video

  • @Typtick
    @Typtick 2 ปีที่แล้ว +1

    I was literally googling this today to have a good optimized scripts xD

    • @Typtick
      @Typtick 2 ปีที่แล้ว

      anyway you are my savior

  • @lucasfarias1148
    @lucasfarias1148 2 ปีที่แล้ว +3

    Hi Taro, great video!
    Could you also do a video about tips for visual studio with (or not) Unity? I see your VS is completely different than mine and also responds way faster to intellisense stuff (e.g. errors).

    • @DavidZobristGames
      @DavidZobristGames 2 ปีที่แล้ว

      He does not use VS he uses rider. Its a paid IDE and the best.

  • @antoniosottomayor6252
    @antoniosottomayor6252 2 ปีที่แล้ว +1

    This helped me out a lot thank you very much. This is very much selfish but more content around this experience level please :). Ty vm

  • @Aryazaky
    @Aryazaky 2 ปีที่แล้ว +1

    THANK YOU

  • @aliengarden
    @aliengarden ปีที่แล้ว +3

    tip : use ctorf to create a constructor with the fields

    • @Tarodev
      @Tarodev  ปีที่แล้ว +1

      Oh wow. Thank you

  • @weckar
    @weckar ปีที่แล้ว +1

    For your singleton code in the UnitManager - would it not be slightly better to make Instance a static property with public read and private write? Prevents it being unset outside the class.

  • @TheSpidermint
    @TheSpidermint 2 ปีที่แล้ว +5

    I am coming back to Unity after about a year so this has helped blow away some cobwebs, thanks for that. I would suggest as a side note Events are technically a way to communicate between scripts without dependency at all. I am trying to use more event based logic to prevent reference breakage and dependency issues. I don't know how events compare in terms of performance/speed?

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      They're perfectly fine and certainly something I should have included in this tutorial... Honestly didn't even cross my mind, lol!
      But please, only decouple if you need to.

    • @MarkRiverbank
      @MarkRiverbank 2 ปีที่แล้ว +1

      @@Tarodev I was coming here to suggest that might be a better way for the Unit to communicate to the UnitManager, to keep it better decoupled and to avoid the Unit managing the UnitManager. I don’t like child objects telling parent objects what to do…I brought those little buggers into the world, I can take them out.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      @@MarkRiverbank Hahaha!

  • @monishdhayalan2552
    @monishdhayalan2552 2 ปีที่แล้ว

    Tarodev is the best unity channel on youtube, change my mind.
    .
    .
    .
    .
    you cant

  • @AB-xr7df
    @AB-xr7df 10 หลายเดือนก่อน

    Nice video.
    Do you have any opinions about when to use events (from my understanding: when you have a one-to-many relationship between components/classes, or when you need to check for "changes" you can use them instead of directly polling)? Though, I suppose if you are just subscribing to events, you still need a reference to the object whose event you are listening for. So, maybe a better question is, what are your thoughts on something like an Event Channels/Busses? Have you used them before?

  • @MattFenner23
    @MattFenner23 2 ปีที่แล้ว +3

    Takes a bit of getting used to, but you can also use a dependency injection library like Zenject (not affiliated). Saves you from having to wire up all the different references manually. Each class just asks for what they need and it gets given to them by the DI library.
    This also stops you needing singletons (the static Instance fields), which are generally considered bad practice, since they make unit testing difficult.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      You know, I use so much DI in my dayjob, but never use it in game dev. Does it translate well?

    • @Wobling
      @Wobling 2 ปีที่แล้ว +1

      @@Tarodev It does, makes life a lot easier in the long run. Making a prototype? Avoid it but making a long term project I couldn't recommend it enough (Zenject

    • @umapessoa6051
      @umapessoa6051 2 ปีที่แล้ว +1

      I tried using DI libraries like Zenject but i couldnt found any benefit from using it, idk if thats just because of the bad tutorials i watched, maybe if Tarodev teach us it would make sense.

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      @@Wobling I'll jump in and take a peak

    • @MattFenner23
      @MattFenner23 2 ปีที่แล้ว +1

      @@Tarodev I feel like it is the secret sauce I have been missing all this time. Obviously you want a DI Container made specifically for Unity, and it's overkill for a tiny project or a prototype.

  • @phil-prod-206
    @phil-prod-206 2 ปีที่แล้ว

    Nice, thank you. I feel like this was targeted right to me and where I'm at right now with Unity/C#, and what I'm struggling with.

  • @leo8292
    @leo8292 2 ปีที่แล้ว

    I just came across an interesting use case that completely contradicted your advice at 3:42! Not saying this to antagonize, but rather to share a funny case of “write code for what you need” and not based on some random advice.
    I wrote a movement behaviour that expanded some navmesh functionality, and I was using a Waypoint : MonoBehaviour object as the cached reference type. Waypoint is kind of a n-Ary tree node kind of class.
    But turns out that the moment I wanted to allow for the bots to chase each other and the player, I realised the mistake I made - Had to refactor the entire code to use Transforms instead, otherwise requiring any and all game objects that needed to be chased to have the waypoint component - creating unnecessary memory overhead, and unnecessary complexity.
    Still needed to access the neighbour nodes in some instances, but a few get components here and there outside of the update loop can’t hurt that much? Oh well
    Fun times!

  • @user-wy6pb8ek1d
    @user-wy6pb8ek1d 2 ปีที่แล้ว

    thanks man

  • @user-up3on6sp4d
    @user-up3on6sp4d 2 ปีที่แล้ว +2

    Cool! But can you do the same thing but one step forward using zenject?

  • @rafarodriguez4765
    @rafarodriguez4765 2 ปีที่แล้ว +1

    Useful

  • @kitsunderedesu
    @kitsunderedesu ปีที่แล้ว

    Hi, your second to last method seemed similar to dependency injection. I had a question about if you had to inject more than one class, how would you do that? It seems like it only works when you have a reference to one.

  • @bv5191
    @bv5191 2 ปีที่แล้ว +1

    Yea, that obj.GetComponent() mistake is one that is taught a lot as a way to do it.

  • @kennethbailey9802
    @kennethbailey9802 2 ปีที่แล้ว +1

    Thanks

  • @septiannabilah4779
    @septiannabilah4779 2 ปีที่แล้ว

    Hey Bro, I really like your video and already implemented a few of them especially the async one. But this time i dont know why when i try to implement the this object reference specifically the collision one is not working in my script. maybe there is need some setup or preparations ?

  • @ahmetdastan8253
    @ahmetdastan8253 2 ปีที่แล้ว +1

    Best openining maker

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +1

      Glad somebody appreciates it :D

  • @kristoferknutsen5334
    @kristoferknutsen5334 2 ปีที่แล้ว +2

    Can you do a bit about Dependency Injection? :)
    Awesome vid btw!

  • @ahmedhafez8698
    @ahmedhafez8698 ปีที่แล้ว

    I liked the video.Thanks to the author

    • @Tarodev
      @Tarodev  ปีที่แล้ว

      You are welcome

  • @AlbertoMiorin
    @AlbertoMiorin ปีที่แล้ว

    Hey. Regarding the example of the list, I usually declare it public static, so that it's generally available throughout the whole application without creating extra objects such as the "public static UnitManager Instance", so that I would have a single class creating that list and with an extra keyword have it publicly available everywhere.
    Is it a bad practice or does it have some major flaws?
    Thanks for this and all your videos!

  • @seppukun208
    @seppukun208 ปีที่แล้ว +1

    I use send message. I have a script that detects collisions for instance as a child somewhere, maybe on an arm or leg. And it make it send a OnCollisionArmEnter() message upwards. And it works fine for the relatively speaking occasional send.
    Kinda set and forget and the script in the parent doesn’t need to go find the dependency or anything.
    I wouldn’t use it on an update loop though.

  • @DissolvedMotions
    @DissolvedMotions 2 ปีที่แล้ว +1

    What would be really awesome if you made a video of is a: Damage over Time / Debuff system.
    There are very few videos/resources about this (only kinda basic ones).
    Example:
    * Poison DOT
    * Fire DOT
    * Slowness
    * Stun
    * And how to increase the durations, damage values of DOTs, damage stacking, etc.

    • @DanPos
      @DanPos 2 ปีที่แล้ว +2

      Sorry to jump in but I've got a video on my channel about creating a magic system in unity using scriptable objects that covers some of this stuff

    • @Tarodev
      @Tarodev  2 ปีที่แล้ว +3

      @@DanPos Dan saves the day!

    • @DanPos
      @DanPos 2 ปีที่แล้ว

      Hope it's not too cheeky to do so

  • @YOSFP
    @YOSFP 2 ปีที่แล้ว +1

    NICE

  • @highimpact1
    @highimpact1 2 ปีที่แล้ว +1

    Not gonna lie, some big brain tips here.

  • @toshitosliba4737
    @toshitosliba4737 2 ปีที่แล้ว

    To have a getter for a list, dictionary and even normal array I personally prefer to do this way.
    public IEnumerable GetUnits()
    {
    foreach(var unit in units)
    {
    yield return unit;
    }
    }
    So this way no matter if it is a list or an array it will always return the elements.

  • @Any1SL
    @Any1SL 2 ปีที่แล้ว

    In c# 6 if you remove the private set property then you can only set the property in the constructor

  • @eleocraft278
    @eleocraft278 2 ปีที่แล้ว +2

    When I'm using static instances I like to use properties with a setter that throws an error when the class is instantiated a second time. Just to prevent errors. Also I would name the static variable singleton because that's what it is really.

    • @user-hb7py7xy7b
      @user-hb7py7xy7b 2 ปีที่แล้ว

      Jon's Skeet "C# in Depth" have a good examples for this pattern including thread-safe implementetion.

  • @Kelvin.Z.
    @Kelvin.Z. ปีที่แล้ว

    Noob question here: is the Init() solution in video a kind of "dependency injection"?