- Home /
Best way to access a private variable from another script (same GO) ?
Hi,
So I have script A and script B on the same GameObject, that have a rigidbody. In script A I have a private variable type Rigidbody that I assign in Start function with GetComponent. Now I want to access the rigidbody from script B. I found a lot of methods online but as I'm new I don't know which is the best and I would take good habits.
My first though was assigning it as well in script B same as script A, but idk it do not seems very optimized? Or I can change from private to public static variable? Or in the start of script B I can use a GameObject.Find then a GetComponent? I'm learning Unity so I would really now how someone good at programming would do for accessing the rigidbody in that case :)
Thanks !
Answer by Nebukam · Jun 15, 2018 at 10:31 PM
By definition private members are not accessible from outside the class itself. Best way to go is to make it public in A so you can access it from B, however be aware that this is an implicit dependency (meaning if you have script B but not A on a GO, B won't be happy). You can make sure A is always present when using B via RequireComponent to make the dependency explicit : https://docs.unity3d.com/ScriptReference/RequireComponent.html
There's other ways (many other ways !) to achieve the same result, it all boils down to how your project is architectured and what kind of interactions you want between them. There's not "bad" solution per-say, although GetComponent is way faster than GameObject.Find. Since you know what you're looking for, and it should exist, GetComponent is the way to go.
Thanks for that answer! Ok so I might make it public and use GetComponent :)
Since in every tutorial I was seeing the rigidbody as a private variable I was wondering if there was an issue with it being public. Also, do I have to make it a static public variable or just a public will do the trick?
Public is fine, static is aimed at making your variable available pretty much everywhere in your code and comes with other constraints (roughly, always point to the same memory address, no matter the instance)
Answer by chetan312 · Jun 16, 2018 at 07:03 PM
if the both scripts are on same game object, you can use GetComponent<>() command otherwise first access the other Gameobject by using GameObject.FindWithTag () and then access the script attached to it.
Your answer
![](https://koobas.hobune.stream/wayback/20220612164838im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Can you make a variable modifiable ONLY by the Inspector? 2 Answers
Script not responding to public variable change 1 Answer
Accessing variable from a method in another script and gameObject 2 Answers
Access variable from another script? Health! 3 Answers
Can I access variables of scripts that inherit from abstract classes? 2 Answers