Object References in Unity - How to Communicate Between Scripts
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
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
Жыл бұрын
haha thank u bro!! I was googling "unit vs gameObject unity" lol trying to find documentation XD
@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
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.
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
2 жыл бұрын
same here!
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!
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!
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.
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.
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!
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. :)
oh my goodness, this video was just what I needed that public static Class Instance trick is just beautiful
You're the best Unity channel out there. I feel like some of the other KZreadrs barely know what they are talking about.
I have been using Unity for more than one year and never knew about the Instantiate trick, Thanks you !
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
this is an incredibly helpful reference especially for beginners!
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
2 жыл бұрын
Thanks for the beard compliment ❤️
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
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
2 жыл бұрын
Sometimes my jokes can be a little off-base 😂
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!
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
2 жыл бұрын
You're welcome. So glad I could help you out 😊
@francescagreetham1804
2 жыл бұрын
@@Tarodev very excited to work my way through all your videos! 😁
Thanks for covering these topics in some of the recent video. It's on point and done well!
@Tarodev
2 жыл бұрын
You're welcome Aj
I loved the opening bro, thanks for the video. It's all good information for beginners.
ty for all the vids, PLX dont stop doing! i'm learning so much!
Took me way too long to find this video. Now I need to do some re-writing. Thanks for this awesome video!
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
2 жыл бұрын
Yup, great suggestion. Also you could turn your unit manager into a proper repository and just expose api-like functions.
Amazing video! I found it extremely useful and it is even more useful for beginners.
Awesome stuff man, I really appreciate the quality of your content! :)
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.
Very useful staff! Got some new ideas for my project :) Thanks man
Great and informative video as usual!
Lot's of useful tips , thankyou!
Thank you, new dev. Super informative. Subbed!
Tarodev: Making us all better by the video!! 🎉
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!
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.
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
2 жыл бұрын
All drugged up and feeling good?
@lechauffagiste2240
2 жыл бұрын
@@Tarodev yes everything is fine, just a few hallucinations where I see you in a cat or in a sponge bob
Great content, keep it coming!
Excellent video, this is exactly the type of stuff I need! Would love a coaching session perhaps in the future xD
Really great video, I learnt alot! legend
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
Жыл бұрын
Welcome aboard
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.
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
Жыл бұрын
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.
Hey, thanks for thoses really cool tips and example !
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
Жыл бұрын
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
Жыл бұрын
@@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
Жыл бұрын
@@rhyspuddephatt Gotcha. I agree. UnityEvents are perfect for handing off the a game designer for use in the inspector!
@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
Thanks man, great videos!
Great Content !! , thanks for all the Videos :)
Thank you taro ❤️
Awesome content (AGAIN) thank you!
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)
Great video man.
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.
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.
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
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
10 ай бұрын
Sounds like you're hungry to learn, so keep going and you'll be a pro
@alextheguy4469
10 ай бұрын
@@Tarodev fingers crossed!
Love your videos. Get to learn something different about coding in each one
Abyss Watcher Boss art on the wall 😍😍😍
@Tarodev
2 жыл бұрын
One of the most badass bosses of all time
Tarofangay here. Thanks for the great video! Gonna watch & take notes from everything you mention.
@Tarodev
2 жыл бұрын
Enjoy buddy, thanks for the suggestion
@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!
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
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...
Aaaaaah, Unity annexed the C# constructors. That explains a lot. Thanks!
The man is a genius
Thank you!
Great vid.
Very helpful. Unity Learn touched on this but didn't give this style of example to see how it works.
Finding game objects and getting components since the journey began 😂
I loved this
Also i'd love to have your input about design patterns in Unity
@Tarodev
2 жыл бұрын
More advanced patterns? If you're after beginner ones I just did a video on a few :)
@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
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
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
2 жыл бұрын
@@fmproductions913 hey thanks for your awnser and clarification about singletons here ! :)
I was literally googling this today to have a good optimized scripts xD
@Typtick
2 жыл бұрын
anyway you are my savior
THANK YOU
thx. a great tutorial for beginners. There was overcoocked 2 ost background of the tutorial. xD
I like your video, cool thumbnail :)
@Tarodev
2 жыл бұрын
Thanks mandy
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!
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
2 жыл бұрын
You're right, I wish I added DI to this video
tip : use ctorf to create a constructor with the fields
@Tarodev
Жыл бұрын
Oh wow. Thank you
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
Useful
I liked the video.Thanks to the author
@Tarodev
Жыл бұрын
You are welcome
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
2 жыл бұрын
You know, I use so much DI in my dayjob, but never use it in game dev. Does it translate well?
@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
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
2 жыл бұрын
@@Wobling I'll jump in and take a peak
@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.
Thanks
thanks man
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.
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!
Yea, that obj.GetComponent() mistake is one that is taught a lot as a way to do it.
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.
Tarodev is the best unity channel on youtube, change my mind. . . . . you cant
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
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
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
2 жыл бұрын
@@MarkRiverbank Hahaha!
Best openining maker
@Tarodev
2 жыл бұрын
Glad somebody appreciates it :D
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
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
2 жыл бұрын
@@DanPos Dan saves the day!
@DanPos
2 жыл бұрын
Hope it's not too cheeky to do so
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
2 жыл бұрын
He does not use VS he uses rider. Its a paid IDE and the best.
NICE
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.
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!
Can you do a bit about Dependency Injection? :) Awesome vid btw!
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.
Not gonna lie, some big brain tips here.
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
2 жыл бұрын
Jon's Skeet "C# in Depth" have a good examples for this pattern including thread-safe implementetion.
Thanks, I went from almost being able to solve a problem to having no idea what is going on
@Tarodev
Жыл бұрын
I hope in a good way?
Blew my mind when you stored the unit as a Unit script and not a GameObject and didn't need to get any components. I fell for that too :(
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?
~I'm going to teach you something that you've been trying to comprehend for 30 years, but has alluded you for all of that time.~ "Thank you for trying, but that's Impossible." *Tarodev waves his hands, flips over 4 playing cards, and says "You've got this."* "Whoa! I now know how the stars are ordered and the planets aligned." *Heads over to the Patreon and says "GIVE ME MOAR!!*
Cool! But can you do the same thing but one step forward using zenject?
Good info for me I'm super new :]+
@Tarodev
2 жыл бұрын
Good luck with your journey guy!
@Betruet
2 жыл бұрын
@@Tarodev keep making great content like this and I won't need luck
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
2 ай бұрын
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.