0

Can you tell me how to access a variable of a script from another script? I have even read everything in unity website but I still can’t do it. I know how to access another object but not another variable.

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

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

Thank you

6
  • int foo = GetComponent<YourScript>().YourVariable Commented Aug 14, 2018 at 5:49
  • @FCin Dont answer in the comments, make it an answer ;) Commented Aug 14, 2018 at 5:51
  • @WhiteMaple I'm too lazy Commented Aug 14, 2018 at 5:52
  • @FCin thanks! With this I can access the variable from the other script. So how can I change the other variable on the other script? Commented Aug 14, 2018 at 5:54
  • @FCin Like for example scriptB has a isAlive=true boolean. I want to change it to false from scriptA? Commented Aug 14, 2018 at 5:55

1 Answer 1

0

Your question is answered here:

https://answers.unity.com/questions/7555/how-do-i-call-a-function-in-another-gameobjects-sc.html

Basically, you create a variable of type "ScriptA" inside script B and put the gameobject containing script A inside the value field of that variable. Then you can access all public functions and variables of script A in script B.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I'm a bit naive in scripting yet. Can you provide a very basic/simple example?
I currently don't have unity installed on my system, but if you follow the code samples provided in the link i gave, you should see a field "ScriptA" in the inspector of the gameObject containing the script B. You then create an empty game object containing script A (or use the gameObject that already contains script A) and simply drag and drop it into the field.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.