count how many times a scene is loaded
i have a player, when it dies the scene is reloaded. i want to limit the reload to 3 times and then show game over scene how should i code this?
Answer by Nomenokes · Feb 10, 2018 at 05:47 PM
Use a static
variable, one that can't be instantiated or destroyed even when changing scenes.
public static int reloadedNum=0;
//later on
if(reloadedNum<3){
reload();
reloadedNum++;
}
else{
gameOver();
}
@Nomenokes I'm a complete beginner I don't have much coding experience I put a void oncollision2d(collision2d col) to load the current scene again ,so how should I apply this to what you wrote.
Ok I see. Do you have a big script for your player? If so, put the static variable there and do the "later on" in the OnCollisionEnter
or whatever you have as a trigger device
@Nomenokes I'm confused This script is attached to my floor when the player touches the ground the scene is reloaded
public class dying : $$anonymous$$onoBehaviour { [SerializeField]Transform spawnpoint;
void OnCollisionEnter2D(Collision2D col) { if (col.transform.CompareTag ("Player")){ col.transform.position = spawnpoint.position; Scene$$anonymous$$anager.Loadscene(Scene$$anonymous$$anager.GetActiveScene().name); } } } So how should I make the appropriate changes to this to stop reloading more than 3 times?really appreciate your help.thank you very much
public class dying : $$anonymous$$onoBehaviour {
static int timesReloaded=0;
[SerializeField]Transform spawnpoint;
void OnCollisionEnter2D(Collision2D col) {
if (col.transform.CompareTag ("Player"){
if(timesReloaded<3){
col.transform.position = spawnpoint.position;
Scene$$anonymous$$anager.LoadScene(Scene$$anonymous$$anager.GetActiveScene().name);
timesReloaded++;
} else {
Scene$$anonymous$$anager.LoadScene("gameOverScene);
}
}
}
}
Do you see how that would work?