Variable being reset to default after being set
I've created a simple boolean variable, DoneLoading, to keep track of when a function is finished executing. DoneLoading is initialized to False, and at the end of the public function, it is set to True.
I call SetSpawnLocation() from another script, and when I print DoneLoading at this point I can see that it IS being set to True. However, when I print out the value of DoneLoading on every OnUpdate() cycle, I've found that it gets set back to false and stays false.
EDIT: After further testing, it looks like somehow, inexplicably, the Start() function is being called AFTER SetSpawnLocation(). However, in my main script, GameManager, the gameObject below is instantiated BEFORE I make a call to SetSpawnLocation(). Why would the Start() function be delayed for so long after instantiating?
Also, is there a way to prevent Start() from wiping out and resetting my variables?
private bool doneLoading;
private void SetSpawnLocation(SpawnLocation curLocation)
{
if (curLocation == SpawnLocation.Tropical) {
commonSprites = commonTropicalSkins;
uncommonSprites = uncommonTropicalSkins;
rareSprites = rareTropicalSkins;
ultrarareSprites = ultrarareTropicalSkins;
}
doneLoading = true;
}
void Update() {
print(doneLoading);
}
I've searched through my code, and doneLoading is only referenced in 3 places: the initial definition, when it's set to True inside SetSpawnLocation(), and when I print it out in OnUpdate().
Please please someone help me. I'm going crazy here. This is happening with all non-class variables in this script - they keep being reset when the script updates.
I'm assu$$anonymous$$g you're setting your variables in a Start method but if you're calling SetSpawnLocation from another Start method then it's not guaranteed to run after the other one. If you need one Start method to run first you could use the Awake method ins$$anonymous$$d.
Answer by games247unity1 · Dec 22, 2016 at 02:34 PM
@steelfeathers : This could be because you are calling SetSpawnLocation() from a co-routine. I am seeing exactly this behaviour in the game I am developing. A function is called, setting the bools, except that they do not stay set!
Curiously, the same function works when called from somewhere else. The only difference that I can see is that the co-routine that calls the fn is from a different monobehaviour.
This seems like a bug in Unity3D, or perhaps it is some special case of subroutines that we do not clearly understand.
Your answer
Follow this Question
Related Questions
i am making a pong game and it works fine till i reset the game 1 Answer
How to change the player gravity level?,How to change the value of the players gravity? 1 Answer
Access variable from different class 1 Answer
Set a variable from another script 1 Answer
How to Modify a java Script variable with a c# Script 1 Answer