- Home /
Many ways to access other components got me very confused.
After scouring the Answers section I emerged more confused than enlightened. When do I use what? Am I understanding this correctly?
GameObject.Find - returns a game object, not a component.
transform.Find - returns the transform of a game object that is a child to the one that the script is attached to.
GetComponent - returns a specified component from another object. (From what I understood that's the only way to directly address components other than scripts in other game objects through an outside script.)
static anything - doesn't need to be instanced and can be accessed with the Dot operator.
So lets say I have a Box, a Ball and a Tri each with a script. Box has a public int, Ball has a public static int, Tri has private int and a child object that has a transform.
So my question is, what would I use to access each of these. I really hope someone can clarify this for me.
I have read the documentation and watched the video in the tutorials section, so I know how to use them, I just can't understand when.
P.S: Where does GetType fit here?
Don't forget Send$$anonymous$$essage ^ ^
GetComponent allows you to cache a component enabling you to access it as if variables in the same script, saving on processing.
You normally require to Find the object you want to cache the component of.
Answer by IvovdMarel · Jun 19, 2014 at 07:57 PM
First of all, never use GameObject.Find/transform.Find, it's slow and there's never a good reason to use it in your game. Besides that, since it's string based, it's not type-safe and especially in bigger projects this might/will lead to errors.
Static variables are not used for single objects such as a Box or Ball, but rather for system scripts such as a ServerManager, UIManager, GlobalVariables etc.
The best way to access these objects to each other, depends on what relation they have to each other. Let's say they're all in a game, perhaps there should be a GameManager that handles the creation (and stores them as variables) and possibly even the interaction.
Take a look at using the Unity Inspector, since this is an easy and typesafe way of referencing objects/scripts.
GetType does not fit in there. It is used to get a class-type, not a reference to the object
If you must use GameObject.Find, try to restrict it to Start() for $$anonymous$$imal impact. Also using TAG based Find is a lot quicker.
Your answer
Follow this Question
Related Questions
How to access the interface from the last component in the inspector 2 Answers
GetComponent keeps returning null 3 Answers
How to get script from Object with (Clone)'s script? 2 Answers
How to get a component from an object and add it to another? (Copy components at runtime) 12 Answers
Inheritance vs RequireComponent -1 Answers