- Home /
Accessing variables in another script using GetComponent()
I've just run across a showstopper when I built a webplayer version of my game, oh dear=S At a certain point in my game I initiate a timer on a script attached to my player character that, when it runs out, sets a variable on a script attached to an npc to true, which causes it to move along it's waypoints etc.
It works fine in the editor, hence why I didn't see any problem previously, but it doesn't work in a webplayer or a standalone app. I tested using one of my guiText functions to show a message after the variable has been set - I never see this message outside the Editor so it looks like the variable is not being set. If I set the isMoving variable to true initially, the npc moves as expected, so the problem must lie with the way I am accessing the variable on the other script.
My code at the moment is below (note I have commented out the line that finds the npc gameobject since I have moved this into the Start()
function:
if(sinkTimer > cleanerResponseTime){
// cleaner = GameObject.Find("cleaner");
otherscript = cleaner.GetComponent("wp_scriptNew1");
otherscript.isMoving = true;
if(otherscript.isMoving){
TextHints.message = "isMoving is true";
TextHints.textOn = true;
}
}
I should point out that multiple npcs have this script attached so I cannot use static variables. I tried to use the method described in the docs here for exposing references to other objects, but I get a warning that a local variable called otherscript already exists. That's true since the code that initiates the timer stores its reference to another script in a variable called otherscript too. However, I have not declared these variables at the top of my script so I assumed they could be treated as temporary variables? (like when using 'i' in a for loop for example).
Renaming one of them and using the code from the docs allows it to work, so:
var otherscript2 : wp_scriptNew1;
function Update(){
if(sinkTimer > cleanerResponseTime){
otherscript2.isMoving = true;
if(otherscript2.isMoving){
TextHints.message = "isMoving is true";
TextHints.textOn = true;
}
}
}
But I still don't understand why using GetComponent didn't work, since the other piece of code which still uses it successfully sets a boolean to start the timer above in the first place.
Without seeing your whole script I can only speculate that you had a globally scoped variable called otherscript of a specific type other than wp_scriptNew1.
Your answer
Follow this Question
Related Questions
updating a gameobject variable from another script attached to another object 3 Answers
Accessing components via script and assigning randomized values to their parameters? 1 Answer
Passing a Variable to an Instance 2 Answers
Get variable from other GameObject's script 3 Answers
GetComponent - problem with var from another script 1 Answer