Object References in Unity - How to Communicate Between Scripts

  Рет қаралды 112,242

Tarodev

Tarodev

2 жыл бұрын

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

Пікірлер: 317
@Tarodev
@Tarodev 2 жыл бұрын
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 Жыл бұрын
haha thank u bro!! I was googling "unit vs gameObject unity" lol trying to find documentation XD
@flyingdutchman2692
@flyingdutchman2692 Жыл бұрын
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 жыл бұрын
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.
@M0usEzPivotz
@M0usEzPivotz 2 жыл бұрын
same here!
@RobinDoesUnity
@RobinDoesUnity 2 жыл бұрын
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!
@lyrion0815
@lyrion0815 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 жыл бұрын
Yup, great suggestion. Also you could turn your unit manager into a proper repository and just expose api-like functions.
@GameDevNerd
@GameDevNerd 2 жыл бұрын
I work with Unity professionally and these videos are high quality, no nonsense. A design pattern I like a lot and don't even know the name of (don't think it has one) is to add a static List property in a MonoBehaviour. If the MonoBehaviour is called Unit it would look like this: public static List AllUnits { get; private set; } = new List(); The key is to add new objects when they're created or enabled and remove them when they're destroyed or disable. So you'd be adding them in either Start, Awake or OnEnable with List.Add and then removing them in OnDestroy or OnDisable with list.Remove. Which one you choose depends on the behavior you want the list to have -- whether you want disabled things to stay in the list or to be removed from it. Of course there's a bit of extra code needed like making sure you don't add an object more than once and stuff, but that's the gist of it. The end result is that now you have a static list in your code you can access at any time and find all objects that have a Unit component! You can query this list for all sorts of things, like maybe you want to find all your units whose health is < 30 so a healer unit can go to them and heal them or maybe you want all units whose health is > 80 to do an attack. This makes it easy! Of course, I advise programmers NOT to use Linq queries again and again in a game loop and never use them every frame. They can be slow and expensive when it comes to garbage collection if abused. So only use those things at key moments like when the game is starting or loading or every now and again when special events take place. Otherwise, you should write out queries manually in a static method or something using a for loop. Oddly enough, there are some cases where a complex Linq query will actually be faster than an algorithmic query a person writes by hand because Microsoft has optimized the hell out of that type of query. So definitely research and test things you're unsure about -- the nuances can be a bit complicated! In any case, this design pattern I showed here makes it easy to find every object with a certain Component (such as Unit) at any time by simply accessing your Unit.AllUnits list! You can take this a step further by adding the Observer Pattern to things and firing events like an OnSpawn and OnDelete (name them what makes the most sense based on how you're using your objects). Then other classes can subscribe to that event in case they need to know when these things are happening! 🙂
@gadgetboyplaysmc
@gadgetboyplaysmc 2 жыл бұрын
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.
@oliversdouglas
@oliversdouglas Жыл бұрын
oh my goodness, this video was just what I needed that public static Class Instance trick is just beautiful
@calvindebeverly7410
@calvindebeverly7410 Жыл бұрын
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.
@rhyspuddephatt
@rhyspuddephatt 2 жыл бұрын
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 Жыл бұрын
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
@KevinTrans
@KevinTrans 2 жыл бұрын
I have been using Unity for more than one year and never knew about the Instantiate trick, Thanks you !
@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!
@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!
@lunkums
@lunkums 2 жыл бұрын
this is an incredibly helpful reference especially for beginners!
@ZahhibbDev
@ZahhibbDev 2 жыл бұрын
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. :)
@gattra
@gattra 10 ай бұрын
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
@windwalkerrangerdm
@windwalkerrangerdm 2 жыл бұрын
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 ❤️
@tobihendrix1324
@tobihendrix1324 Жыл бұрын
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.
@Warwipf
@Warwipf 2 жыл бұрын
You're the best Unity channel out there. I feel like some of the other KZbinrs barely know what they are talking about.
@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
@michalbalicky4797
@michalbalicky4797 2 жыл бұрын
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.
@ulricleprovost707
@ulricleprovost707 2 жыл бұрын
Also i'd love to have your input about design patterns in Unity
@Tarodev
@Tarodev 2 жыл бұрын
More advanced patterns? If you're after beginner ones I just did a video on a few :)
@ulricleprovost707
@ulricleprovost707 2 жыл бұрын
@@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 жыл бұрын
@@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 жыл бұрын
@@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 жыл бұрын
@@fmproductions913 hey thanks for your awnser and clarification about singletons here ! :)
@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
@luckyknot
@luckyknot 9 ай бұрын
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.
@meshavorazoon979
@meshavorazoon979 2 жыл бұрын
Abyss Watcher Boss art on the wall 😍😍😍
@Tarodev
@Tarodev 2 жыл бұрын
One of the most badass bosses of all time
@larryd9577
@larryd9577 2 жыл бұрын
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.
@vaulb
@vaulb Жыл бұрын
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
@calinzavoi
@calinzavoi 2 жыл бұрын
Amazing video! I found it extremely useful and it is even more useful for beginners.
@thumbwiz
@thumbwiz Жыл бұрын
Took me way too long to find this video. Now I need to do some re-writing. Thanks for this awesome video!
@machlordundead
@machlordundead 2 жыл бұрын
ty for all the vids, PLX dont stop doing! i'm learning so much!
@amogh2101
@amogh2101 2 жыл бұрын
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
@DanPos
@DanPos 2 жыл бұрын
Great and informative video as usual!
@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 😂
@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!
@MIDGETPANCAKES
@MIDGETPANCAKES 2 жыл бұрын
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.
@TriCombStudio
@TriCombStudio 2 жыл бұрын
Thank you, new dev. Super informative. Subbed!
@marcinlewandowicz
@marcinlewandowicz 2 ай бұрын
Awesome stuff man, I really appreciate the quality of your content! :)
@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.
@AndrewNostromo
@AndrewNostromo 2 жыл бұрын
Great content, keep it coming!
@Ricochetaglet
@Ricochetaglet 10 ай бұрын
Tarodev: Making us all better by the video!! 🎉
@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 жыл бұрын
You're welcome. So glad I could help you out 😊
@francescagreetham1804
@francescagreetham1804 2 жыл бұрын
@@Tarodev very excited to work my way through all your videos! 😁
@MyLOBsTerr
@MyLOBsTerr Жыл бұрын
Very useful staff! Got some new ideas for my project :) Thanks man
@SteffDev
@SteffDev Жыл бұрын
Lot's of useful tips , thankyou!
@PixelbugStudio
@PixelbugStudio 2 жыл бұрын
Great video man.
@stevancosovic4706
@stevancosovic4706 Жыл бұрын
Thanks man, great videos!
@ulricleprovost707
@ulricleprovost707 2 жыл бұрын
Hey, thanks for thoses really cool tips and example !
@Sackwiz
@Sackwiz Жыл бұрын
Excellent video, this is exactly the type of stuff I need! Would love a coaching session perhaps in the future xD
@Eagle-pe9pg
@Eagle-pe9pg 2 ай бұрын
Awesome content (AGAIN) thank you!
@headstart3570
@headstart3570 Жыл бұрын
Really great video, I learnt alot! legend
@SweetHoneycode
@SweetHoneycode 2 жыл бұрын
Very helpful. Unity Learn touched on this but didn't give this style of example to see how it works.
@endorphingames2957
@endorphingames2957 Жыл бұрын
Love your videos. Get to learn something different about coding in each one
@svendpai
@svendpai 2 жыл бұрын
Thank you taro ❤️
@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.
@alextheguy4469
@alextheguy4469 10 ай бұрын
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 ай бұрын
Sounds like you're hungry to learn, so keep going and you'll be a pro
@alextheguy4469
@alextheguy4469 10 ай бұрын
@@Tarodev fingers crossed!
@paulshepherd300
@paulshepherd300 2 жыл бұрын
Great Content !! , thanks for all the Videos :)
@lechauffagiste2240
@lechauffagiste2240 2 жыл бұрын
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
@pedropc5824
@pedropc5824 2 жыл бұрын
The man is a genius
@jirikucera9731
@jirikucera9731 2 жыл бұрын
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!
@otdewiljes
@otdewiljes Жыл бұрын
Aaaaaah, Unity annexed the C# constructors. That explains a lot. Thanks!
@jarrettonions3392
@jarrettonions3392 7 ай бұрын
Finding game objects and getting components since the journey began 😂
@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)
@adamolesiak6528
@adamolesiak6528 2 жыл бұрын
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
@monishdhayalan2552
@monishdhayalan2552 2 жыл бұрын
Tarodev is the best unity channel on youtube, change my mind. . . . . you cant
@weckar
@weckar Жыл бұрын
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.
@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...
@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 ?
@seppukun208
@seppukun208 Жыл бұрын
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.
@gamepass505
@gamepass505 2 жыл бұрын
Thank you!
@Typtick
@Typtick 2 жыл бұрын
I was literally googling this today to have a good optimized scripts xD
@Typtick
@Typtick 2 жыл бұрын
anyway you are my savior
@MattFenner23
@MattFenner23 2 жыл бұрын
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 жыл бұрын
You know, I use so much DI in my dayjob, but never use it in game dev. Does it translate well?
@Wobling
@Wobling 2 жыл бұрын
@@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 жыл бұрын
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 жыл бұрын
@@Wobling I'll jump in and take a peak
@MattFenner23
@MattFenner23 2 жыл бұрын
@@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.
@eierschaedl
@eierschaedl Жыл бұрын
Since you are showing us a lot of cool stuff here, it would be nice if you educated us a little more in terms of how the things you are doing are called. For example declaring a static UnitManager Instance makes this class a Singleton (right?). Not a word on the pro and cons of that? Adding a setter and getter to "Units" makes it a Property. Maybe your audience "should know" those terms, but they are so crucial for Development in general, they shouldn´t just be ignored. Otherwise, very useful code you are showing here, Thanks a lot!
@bengamedev1872
@bengamedev1872 Ай бұрын
A static reference within that class doesn't mean it's a singleton. You might want to turn it into one (non singleton statics is generally a cursed way to code). Adding a simple Assert.IsNull(instance, "We should be a singleton!") in Awake would do the job.
@bv5191
@bv5191 2 жыл бұрын
Yea, that obj.GetComponent() mistake is one that is taught a lot as a way to do it.
@aliengarden
@aliengarden Жыл бұрын
tip : use ctorf to create a constructor with the fields
@Tarodev
@Tarodev Жыл бұрын
Oh wow. Thank you
@TheKr0ckeR
@TheKr0ckeR 2 жыл бұрын
Tarofangay here. Thanks for the great video! Gonna watch & take notes from everything you mention.
@Tarodev
@Tarodev 2 жыл бұрын
Enjoy buddy, thanks for the suggestion
@TheKr0ckeR
@TheKr0ckeR 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!
@antoniosottomayor6252
@antoniosottomayor6252 2 жыл бұрын
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
@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!
@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.
@DissolvedMotions
@DissolvedMotions 2 жыл бұрын
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 жыл бұрын
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 жыл бұрын
@@DanPos Dan saves the day!
@DanPos
@DanPos 2 жыл бұрын
Hope it's not too cheeky to do so
@RealisiticEdgeMod
@RealisiticEdgeMod 2 жыл бұрын
Great vid.
@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.
@hossein818
@hossein818 2 жыл бұрын
thx. a great tutorial for beginners. There was overcoocked 2 ost background of the tutorial. xD
@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.
@rafaelache8650
@rafaelache8650 2 жыл бұрын
I loved this
@Aryazaky
@Aryazaky 2 жыл бұрын
THANK YOU
@lucasfarias1148
@lucasfarias1148 2 жыл бұрын
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.
@TheSpidermint
@TheSpidermint 2 жыл бұрын
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 жыл бұрын
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 жыл бұрын
@@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 жыл бұрын
@@MarkRiverbank Hahaha!
@thegrey448
@thegrey448 2 жыл бұрын
this what im doing last night. thanks for the tutorial. i created a menu that panel content(gamelist) filled by a bunch buttons prefabs, and after instantiate in awake then i able to click again by listener to instantiate to other panel content(playlist). in this moved i able make button in gamelist interactable = false , and in playlist button interacable = true. my prblem but i can not to remove cloning buttons in playlist back to original in gamelist and make the buttons in game list interacbale tobe true again. would you help me . thanks in advance. edit : in this moved from panel gamelist to playlist im able instantiate one by one the button by listener just need once instantiate each button.
@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!
@AB-xr7df
@AB-xr7df 9 ай бұрын
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?
@user-up3on6sp4d
@user-up3on6sp4d 2 жыл бұрын
Cool! But can you do the same thing but one step forward using zenject?
@kennethbailey9802
@kennethbailey9802 2 жыл бұрын
Thanks
@yosyp5905
@yosyp5905 2 жыл бұрын
I didn't quite get the "Unit" thing. How can a GameObject spawn with Instantiate() if the _unitPrefab is of type "Unit" class?
@TheKr0ckeR
@TheKr0ckeR Жыл бұрын
How should be the communicate between scripts that on the same game object? For example, I have Class A & Class B. I hold the Class A ref inside the Class B. Then i create Class C. It both needs Class A & Class B, so should it just reference Class B and can reach to the Class A there or just define the Class A & B on Class C too?
@fndTenorio
@fndTenorio 2 ай бұрын
3:40 Maybe I'm wrong, but using getComponent is not a mistake. Your "Unit" is a component of a gameObject (in this case a prefab), it is not the gameObject itself. The Unity editor lets you drag and drop for convenience.
@Kelvin.Z.
@Kelvin.Z. Жыл бұрын
Noob question here: is the Init() solution in video a kind of "dependency injection"?
@OXGrekXO
@OXGrekXO 2 жыл бұрын
I'm quite new to game dev so perhaps im doing something wrong. In you Video you replaced the Serialized Reference from GameObject to Unit to get around the GetComponent call. Am i right with the assumption this would not work with en Prefab which maybe has several diffrent MonoBehaviour scripts? As an example say i have an Prefab Unit with scripts UnitMaster, UnitMovement and UnitGravity. The UnitMaster is responsible for the referencing stuff like in your video it manages the Init() methode. The other two scripts are i think clear in their responsibility. If i now replace the GameObject with UnitMaster inside the SpawnerManager it wouldn't instantiate the Prefab but only an GameObject with the master Script or am I guessing wrong (havent tryed it in code only thought experiment). What would be the best way to get to the UnitMaster script for something like this?
@Tarodev
@Tarodev 2 жыл бұрын
You can save a prefab reference by any component the object has. Generally you pick the one which will be used most often
@OXGrekXO
@OXGrekXO 2 жыл бұрын
@@Tarodev so it would work with prefabs, I must try this. Thank you 😁
@HofWasHere
@HofWasHere Жыл бұрын
7:20 why do you need the {get; set;} flags if it works also without? You can access public variables if you already have the instance.
@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
@eleocraft278
@eleocraft278 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.
Unity Code Optimization - Do you know them all?
15:49
Tarodev
Рет қаралды 181 М.
1🥺🎉 #thankyou
00:29
はじめしゃちょー(hajime)
Рет қаралды 78 МЛН
CAN YOU HELP ME? (ROAD TO 100 MLN!) #shorts
00:26
PANDA BOI
Рет қаралды 36 МЛН
How To Render 2 Million Objects At 120 FPS
14:57
Tarodev
Рет қаралды 135 М.
Connecting scripts on the same object in Unity
15:36
Game Dev Beginner
Рет қаралды 10 М.
How to get a variable from another script in Unity (the right way)
15:44
Game Dev Beginner
Рет қаралды 84 М.
10 Things You NEED to Be Doing in Unity
11:40
Tarodev
Рет қаралды 124 М.
Be CAREFUL with Scriptable Objects!
8:27
Code Monkey
Рет қаралды 74 М.
Giving Personality to Procedural Animations using Math
15:30
t3ssel8r
Рет қаралды 2,4 МЛН
Unity async / await: Coroutine's Hot Sister [C# & Unity]
16:18
The Power of Scriptable Objects as Middle-Men
17:41
samyam
Рет қаралды 116 М.
C# Events & Delegates
17:21
Tarodev
Рет қаралды 82 М.