- Home /
Question by
Morokiane · Mar 28, 2014 at 01:08 AM ·
staticstatic variablestatic variables
Static variables not staying
I'm creating a script so a player knows when they collect 5 coins in a row. For some reason, if there is too much time between coin collection Unity resets my variable back to 0...and I'm not sure what is causing this.
public class coin : MonoBehaviour {
static int coinsCaughtInSequence = 0;
void Start(){
coinsCaughtInSequence = 0;
}
void OnTriggerEnter2D(Collider2D collider){
if(collider.tag == "Player"){
coinsCaughtInSequence++;
if(coinsCaughtInSequence >= 5){
Debug.Log ("5 coins collected");
}
Debug.Log(coinsCaughtInSequence);
Destroy(this.gameObject);
}
}
}
Comment
Best Answer
Answer by gfoot · Mar 28, 2014 at 01:18 AM
Whenever you create a new coin, it will reset the counter. Are you sure you're not creating more coins during the game? Maybe move the initialization to zero out of the Start method, or make the player track the number of coins collected instead of using a static for it.