- Home /
Int adding twice instead of once?
In the below code once the player finishes the level it reloads the level with the level being +1 from before. I used brackeys code here for the save/load: https://www.youtube.com/watch?v=XOjd_qU2Ido
The script is definatley only firing once, I have made sure of that as well. The debug.log shows that it fires twice and I have no idea why, any help is appreciated, thanks.
`
public class isLevelDone : MonoBehaviour
{
public GameObject player;
void Start()
{
PlayerData data = SaveSystem.LoadPlayer();
player.GetComponent<Player>().level = data.level;
}
void Update()
{
if (SpawnPitHoles.orcsDead && CollisionShield.arrowsDone)
{
endLevel();
}
}
public void endLevel()
{
SpawnPitHoles.orcsDead = false;
CollisionShield.arrowsDone = false;
player.GetComponent<Player>().level++;
SaveSystem.SavePlayer(player.GetComponent<Player>());
Debug.Log("Level Complete" + " player level is " + player.GetComponent<Player>().level);
Application.LoadLevel(Application.loadedLevel);
}
`
keep a flag to run the update code only once. flag=true on Start().
if (flag && Spawn$$anonymous$$Holes.orcsDead && CollisionShield.arrowsDone)
{
endLevel();
flag=false;
}
which he already does if you read the endLevel
function and the condition
He sets some flags in some other scripts, but its possible that these flags are being set back to true in the update function for the other scripts... its also possible that for some reason he has multiple copies of this script in his scene accidentally. If you implement a static flag that is unique to this script then your issue should go away.
Answer by logicandchaos · Mar 30, 2020 at 04:02 PM
The function probably gets called twice. Try this:
bool gameOver=false;
void Update()
{
if (SpawnPitHoles.orcsDead && CollisionShield.arrowsDone)
{
gameOver=true;
}
if(gameOver)
{
gameOver=false;
endLevel();
}
}