So I have two scripts. One is on a character, and when it “dies,” I set a static variable “Dead” to true. This script is fine and everything works like it is supposed to.
function OnTriggerEnter (hit : Collider){
if((hit.gameObject.tag == "Spikes")&&(GoingToDie == false)){
GoingToDie = true;
var WinstonExplosion2 = Instantiate(WinstonExplosionPrefab, transform.position, transform.rotation);
WinstonExplosion2.transform.parent = gameObject.transform;
yield WaitForSeconds(1);
Dead = true;
GoingToDie = false;
}
function LateUpdate (){
if(Dead){// reset on death
print("dead");
transform.position = GameObject.Find("Character_Spawn").transform.position;
//Dead = false;
// I know I'm not setting Dead back to false, but it doesn't work when I do that..
}
Static variables can be a dicey thing. I generally try to shy away from using them as much as possible, but if you must, try doing this instead:
Make the Dead static variable itself private, and change how it’s accessed from as a variable to methods, like so:
//Changed to private from public. Also changed name of variable itself to catch any places within this script it's being accessed without using GetDead()/SetDead().
private static var IsDead:boolean = false;
static function GetDead():boolean {
return IsDead;
}
static function SetDead(newDead:boolean) {
if (newDead == true) {
Debug.Log("Dead being set to true...");
} else {
Debug.Log("Dead being set to false...");
}
IsDead = newDead;
}
Doing it this way could provide a little more insight on where you could be accessing this, and may illuminate any logical errors within your code. You’ll have to change code to reflect this new way, so:
I think your first problem is caused by the way Update methods are chained. There is no guarantee that LateUpdate on one script will run after Update on a different script.
In any case, this seems to be a weird way to accomplish what you are trying to do. What you should probably do is use GameObject.SendMessage(over here). Move the entire code under the logic in Update to a ResetPosition() method and call it with SendMessage. This will make sure that it will always get called, once. Never try to evaluate static variables that can change every frame - it’s a recipe for disaster. In fact, I would suggest entirely avoiding static variables and methods in this case.
This will also solve a potential future problem, which is that it will get stuck on x = 447.5.
Let me know if this works (and especially if it doesn’t)
Alright, I figured it out… There was nothing wrong with the static variables. I was setting “Dead” back to false in another script before all the other scripts ran, and I hadn’t noticed… But thank you ytanay and pazzesco for the suggestions! I’ll be sure to do something about all those static variables!