- Home /
Do something when something happens in another script.
I have Script01.js and Script02.js. In Script01.js, I have a variable named "animState". animState goes from 0 - 4 throughout the script, depending on what events take place. Now, I want to be able to tell when animState is a certain value in Script02.js. It would be used like this:
if(script01.animState == 3)
{
//Do something
}
I tried making a new instance of the class:
var script01 : Script01;
and then dragged Script01.js into the var slot of the Script02.js.
I inserted a print into Script02.js to see what's happening:
print(script01.animState);
It's value shows up as 0.
Oh, and the scripts are on different objects.
What am I doing wrong, can anyone help me with this?
Thanks,
Kyle
There are a lot of unknowns here. Firstly, can you confirm that your variable is actually changed? Secondly, is your variable static? (if it is, then the first method will work just fine and if not, you will need to get the actual instance attached to the other object, not a new instance unless the value is changed in all instances of the script or something like that).
Answer by HeywoodFloyd · Sep 15, 2010 at 05:06 PM
Instead of a variable for the script on the GameObject, have a variable for the GameObject to which the script is attached. You can get to the script like this:
var objectWithScript : GameObject; //Set this in the inspector window
...
//Get a reference to the script attached to the GameObject
var scriptO1Ref : Script01 = objectWithScript.getComponent(Script01);
(Forgive me if there are some syntax errors; I usually use C#.) The variable script01Ref should let you manipulate the script you care about.
Answer by Cyb3rManiak · Oct 19, 2010 at 12:08 AM
You can use both the solutions given here, but I honestly don't see a problem with how you described you did it. It should work.
I think you just have some other error in your code, you dragged the wrong thing in the inspector or you put the print statement in the wrong place. If you want you can upload your project somewhere, and I can try and take a look. Or you can post the code for both scripts here, and a snapshot of the inspectors...
Answer by Ray-Pendergraph · Dec 18, 2010 at 01:57 PM
The post from HeywoodFloyd got it. What I don't see mentioned yet though is the why. When you drag the .js script onto one GameObject and then drag the .js script onto a MonoBehaviour (script2)... these are two instances of this "class". I say class because underneath, Unity compiles all of the javascript files to classes just like C# and puts them in their own assembly. It's not really a "script" at this point so the variables of the script are not shared. The instance of Script1 inside of Script2 (which Unity has created for you) is not getting updated, in fact it's not doing anything so it's state will remain the default.