- Home /
How to READ a variable VALUE from other Object Script?
Hi, im trying to read a boolean variable value from other object script, but not sure how to do it right, im using this:
On the FROM object Script (called fromScript):
public var myVariable : boolean; // The value that i want to send to other object script.
function Start () {
myVariable = true;
}
On the TO Script on other Object:
var fromObject : GameObject; // The object that contains the from script and the variable value.
var theVariable : boolean;
function Start () {
theVariable = fromObject.GetComponent.<fromScript>(myVariable);
// This value must be "true", cause it reads that value from the myVariable on the fromScript.
}
and the theVariable value must be the same as the myVariable value on the from Object script, but this doesnt works.
Thanks to any help about this.
Answer by ElijahShadbolt · Oct 13, 2016 at 09:18 PM
theVariable = fromObject.GetComponent<fromScript>().myVariable;
And you could change the Start() function in fromScript to an Awake() function, to make sure myVariable is set to true before the TO Script gets that value.
GetComponent<T>() is a function that returns a reference to the fromScript. Then you can access its public variables with a dot separating the reference name and the variable name. For example,
var otherScript : fromScript;
otherScript = fromObject.GetComponent<fromScript>();
theVariable = otherScript.myVariable;
does the same as
theVariable = fromObject.GetComponent<fromScript>().myVariable;
Great, thank you very much, now works perfect (seting the value of the variable on the Awake() function as you mention), just one question, in the actual code the result of the myVariable from the fromScript its in the Update() function, cause is the result of a button pressed, but then the TO Script doesnt reads it, cause it reads false even when the myVariable its changed to true, how can i do to make the TO Script reads this value properly?, thanks again!
Hi again, ok ist Solved, i just place the:
theVariable = fromObject.GetComponent<fromScript>().myVariable;
from the TO Script, into the Update() function ins$$anonymous$$d of the Start() function used before, and now it "updates" correctly :), thanks.
That's totally fine!
Yeah, if you want two value variables (like bool) to be the same, you have to update the other one every time you change the first one.