- Home /
Accessing variables from a different gameobject
I know this question has been asked a million times, but I just can't get my script to work. I'm able to access the varialbe, but it doesn't change like it's supposed to.
if you can edit your question with script I may help you.
Answer by You! · Jun 12, 2012 at 05:48 AM
When you access non-private variables from other scripts, you must follow the following formula:
ObjectName.GetCompontent(ScriptName).VariableName
If the variable is in a script which is attached to the same object as the script which you are using, use this:
GetComponent(ScriptName).VariableName
If the variable refers to an object, you can chain formulas:
ObjectName.GetComponent(ScriptName).VariableNameSetAsObject.GetComponent(ScriptName).VariableName
This only works if the variable is not private. You must change the variable to not be private if it currently is.
That's not really how it works. You need to use GetComponent, unless you're using static variables, which I would discourage unless you know what static actually means.
...correct. I was kinda confused on how GetComponent works until today (when someone helped me on a question of my own). I'm definitely changing the answer.