- Home /
Monobehaviour shared properties across single gameobject
I have a few classes that are derived from Monobehaviour attached to the same GameObject and I was curious to the nature of the GetComponent calls.
If I call GetComponent().transform and GetComponent().transform, my testing has shown that they are the same, even when I do not adjust the values in ComponentB. So is the transform stored once in the GameObject, and accessed by all monobehaviours attached to that game object?
Answer by Intensity3000 · Mar 02, 2013 at 09:27 PM
As to the transform, I believe transform = GetComponent(Transform). When I use the GetComponent function for example it is often when i am creating a reference to another script and its variables. For example I have the script for the player character, PlayerScript, and the WeaponScript. I want to access the damage variable in the weapon script from within the PlayerScript, so in the PlayerScript I would type a variable to the weapon gameobject itself, and the code to create a reference to the script and its variable for damage would be something like this
var damage = weapon.GetComponent(WeaponScript).damage
this would establish a reference to the damage variable within the weapon script, accessible from the character script
Answer by MartinCA · Mar 02, 2013 at 09:35 PM
You are correct, Transform is actually a type of component attached to a GameObject, the only unique thing about Transform is that it is a mandatory component on all GameObjects and you cannot disable or remove it.
That said, all classes deriving from Component ( including Transform and Behaviour/MonoBehaviour which are your scripts ) store quick accessors to common components such as .transform ( see Component Reference Page ).
So in reality, assuming you have a GameObject with Transform component, ScriptA and ScriptB attached to it every reference within those components will point to the said Transform component:
// These are synonymous
transform == GetComponent< Transform >()
// As are these
GetComponent< Transform >() == GetComponent< ScriptB >().transform
// And you can even reference loop to infinity!
transform == transform.transform.transform.transform.transform
Hope this helps!
"Quick accessors" in terms of typing, but not in terms of performance - it's always worth caching transform, animation etc.
This is exactly what I was looking for! I had thought that was the case from what my testing had shown, thank you for confir$$anonymous$$g my suspicions!
Your answer
Follow this Question
Related Questions
Adding Arbitrary Properties to GameObjects 1 Answer
Creating a single-line function for GameObject.Find and GetComponent (for multiple components) 3 Answers
Get components of multiple instantiated objects? 2 Answers
GetComponent vs AddComponent 3 Answers
How to get a variable value from another script(C#)? 1 Answer