- Home /
Duplicate Question
How do I change a variable in Script A from inside Script B
I have a scriptA as a component of gameObjectA, and scriptB as a component of gameObject B.
I have some variables declared and used in scriptA, and I'd like to be able to change them from scriptB.
What are the simplest methods that people would suggest?
P.S. I'm using Javascript, and thanks in advance.
Please search first; this is the most-asked question and must have been answered literally hundreds of times by now.
I promise I did, but the examples I found didn't explain it in a way that helped me solve my problem, I'm afraid.
Answer by aldonaletto · Jul 20, 2013 at 04:50 AM
Scripts in Unity are components (like Renderer, CharacterController, Collider etc.), thus you must get a script with GetComponent(ScriptName). If scriptA and scriptB are both attached to the same object, get a reference to scriptA with GetComponent:
// assuming that ScriptA is the name of scriptA:
var codeA: ScriptA = GetComponent(ScriptA);
codeA.variable1 += 1; // modify the variables
codeA.variable2 = false;
If scriptA is attached to a different object, you must have a reference to this object:
// otherObject is a reference to the other object:
var codeA: ScriptA = otherObject.GetComponent(ScriptA);
codeA.variable1 += 1; // modify the variables
codeA.variable2 = false;
Any reference to the game object or any of its components works (transform, collider, renderer, other script references etc.)
Hmm... what does codeA refer to? And I assume the first line goes before functions with other variable declarations, whereas the other two lines would go in update?
The code above should be part of the function that modifies ScriptA variables. If you're modifying ScriptA in the Update function, place the whole code inside it. If ScriptA is always the same, place the variable codeA outside any function and initialize it at Start, and modify its variables wherever you want - like this:
private var codeA: ScriptA;
function Start(){
codeA = GameObject.Find("ObjectA").GetComponent(ScriptA);
}
function Update(){
codeA.variable1 += 1;
}
Follow this Question
Related Questions
Accessing Other Script Variables (C#) 2 Answers
Adding variables from all scripts 2 Answers
Error Accessing Other Script's Variables 1 Answer
How can I edit my static variable in the editor? 1 Answer
Get script variable from collider 3 Answers