- Home /
How to link this 2 variables from 2 different scripts / gameobjects?
Hi, can someone tell me how to link this 2 scripts? I have read the Script Reference, but I don't understand it. http://unity3d.com/support/documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
I have 2 scripts. In the first I have a variable. If I press on "k" the testVariable in the first script is changed to 5. If testVariable is 5, I need to set anotherVariable in the second script to 1. Can someone explain this to me so I can use this in my other scripts?
First script: testInput.js
var testVariable = 1;
function Update ()
{
if(Input.GetKey("k"))
{
testVariable= 5;
}
}
Second script: testOutput.js
var anotherVariable = 0;
function Update ()
{
if(testVariable= 5)
{
anotherVariable= 1;
}
}
@Bérenger $$anonymous$$antoue, Sorry, but I don't understand your answer. Can you please make a little example with the 2 test scripts? I've been searching long for this, but I can't understand it because my English is not very well. If you can make a example I will understand.
Answer by Berenger · Jun 07, 2012 at 08:04 PM
You can have a reference of testInput inside testOutput and test testInput.testVariable. testVariable could be assigned in the inspector or with a FindXXX function.
Another way would be to have a reference of testOutput inside testInput, so you can call a function testOutput.OnTestVariableChange( testVariable ), the test being inside instead of Update.
Finally, if you're feeling brave, there is singletons.
Here you go.
First script: testInput.js
var testVariable = 1;
var testOutput to; // Assign it in the inspector
function Update()
{
if( Input.Get$$anonymous$$ey("k") )
{
testVariable= 5;
to.UpdateAnotherVar( testVariable );
}
}
Second script: testOutput.js
var anotherVariable = 0;
function UpdateAnotherVar( i : int )
{
if( i == 5) // = is assignation, == is equality test
{
anotherVariable = 1;
}
}
geennam : I got an error on the second line of testInput.js, it is expecting a ;. But it can't find it.
$$anonymous$$e : Well, that's because I code in JS like a penguin with alzheimer wearing boxing gloves. Sort of like that.
Anyway,
var to : testOutput;