Accessing a variable from another C # script

Can you tell me how to access a script variable from another script? I even read everything on Unity website, but I still can't do it. I know how to access another object, but not another variable.

This is the situation: Im in script B , and I want to access the variable X from script A. The variable X is equal to boolean . Can you help me?

Btw I need to update the value of X s in script B , how to do it? Accessing it in the Update function. If you could give me an example with these letters, that would be great!

thanks

+6
source share
3 answers

First you need to get the script component of the variable, and if they are in different game objects, you need to pass the game object as help in the inspector.

For example, I have scriptA.cs in GameObject A and scriptB.cs in GameObject B :

scriptA.cs

 // make sure its type is public so you can access it later on public bool X = false; 

scriptB.cs

 public GameObject a; // you will need this if scriptB is in another GameObject // if not, you can omit this // you'll realize in the inspector a field GameObject will appear // assign it just by dragging the game object there public scriptA script; // this will be the container of the script void Start(){ // first you need to get the script component from game object A // getComponent can get any components, rigidbody, collider, etc from a game object // giving it <scriptA> meaning you want to get a component with type scriptA // note that if your script is not from another game object, you don't need "a." // script = a.gameObject.getComponent<scriptA>(); <-- this is a bit wrong, thanks to user2320445 for spotting that // don't need .gameObject because a itself is already a gameObject script = a.getComponent<scriptA>(); } void Update(){ // and you can access the variable like this // even modifying it works script.X = true; } 
+11
source

just to complete the first answer

no need for a.gameObject.getComponent<scriptA>();
a already a game object, so a.getComponent<scriptA>(); will do a.getComponent<scriptA>();
and if the variable you are trying to access is in the children of the game object, you should use a.GetComponentInChildren<scriptA>();
and if you need a variable or method, you can access it like this a.GetComponentInChildren<scriptA>().nameofyourvar; a.GetComponentInChildren<scriptA>().nameofyourmethod(Methodparams); a.GetComponentInChildren<scriptA>().nameofyourvar; a.GetComponentInChildren<scriptA>().nameofyourmethod(Methodparams);

+1
source

Here you can use static.

here is an example:

ScriptA.cs

 Class ScriptA : MonoBehaviour{ public static bool X = false; } 

ScriptB.cs

 Class ScriptB : MonoBehaviour{ void Update() { bool AccesingX = ScriptA.X; // or you can do this also ScriptA.X = true; } } 

for more details, you can refer to the singleton class.

0
source

Source: https://habr.com/ru/post/975522/


All Articles