- Home /
Howto access a variable in another script?
In level 1 I have an object (obj1) with a script (script1), and a variable (var1). I have attached:
function Awake () {DontDestroyOnLoad (transform.gameObject);}
to script1 to keep it alive when level 2 is loaded. In level 2 i have an object (obj2) that would need to check the variable (var1) in obj1 - script1.
I have tried on obj2:
function Start(){
var checkit : script1 = GetComponent(script1).var1;
Debug.Log(checkit);}
but I think this might only search for the code on the same object, not sure. Could anyone help with how to access the other object, please?
Answer by CodeMasterMike · Feb 07, 2013 at 09:27 AM
In order to get the objects variable, you need to access the component (your case, the script) through the gameobject, something like this:
var other : script1 = obj1.GetComponent(script1);
var variableFromScript = other.var1;
I only use C# so the code might not be right, but hopefully you see the thread of thought here.
Good luck!
I changed to the suggestion, but it continues to give errors. It says: BCE0005: $$anonymous$$ identifier: ´obj1´. Still - Thx for suggestion!
You cant just write 'obj1', it needs to be a valid gameobject before you can try and access the component.
Find the object you want to access (in your case, the 'obj1' gameobject) with a search function like:
GameObject.FindWithTag
or,
GameObject.Find
or attach it to the script by settings a public Gameobject in the class.
THX! Now it seems to work!
function Start(){
var checkit : script1 = GameObject.Find("obj1").GetComponent(script1);
var variableFromScript = checkit.var1;
}