- Home /
set level to be played only 3 times
How to set level to be played only 3 times. Player will only get to Play the level 3 times. Can anybody give some examples of code in C#
3 times each time he runs the game? 3 times in total? Is it the very first or is it manually loaded?
Answer by shriya · Jan 15, 2016 at 01:27 PM
Hi aan_comel,
You just need static counter. In previous answer mistake is at line where we are setting player prefs on button click using counter it should be through fetching playerprefs but as you don't need it so not correcting that.
public static int counter = 0;
void LoadLevel1()
{
if( counter<=3)
{
counter++;
Application.LoadLevel("levelName");
}
else
{
print("level already loaded for three times");
}
}
Thank you for the codes. I set LoadLevel1() to public and attached it to the button that loads the level. But the counter doesn't seem to count. Even I press the button more than 3 times, it doesn't print "level already loaded for three times"
****UPDATE This code works now! But I didn't realize I will not be able to play again, after I exit the game. Do I need to add script to restart again?
Reply to "Update"
You can either have when you exit the game, just before the exit code, you set the counter to 0 and save it.. Or in an Awake() function set the counter to 0 and then save it. :)
Edit: And if you're needing the counter to be reset every time they play, there's no need for "PlayerPrefs" and what not.. You should just be able to get away with making the counter static
Can I just use this code? Or is it not encouraged to do so?
PlayerPrefs.DeleteAll ();
The problem with this code up here might be that you need to add in a PlayerPrefs.Save somewhere. This way the PlayerPref is 100% saved.
Another way to do this would be to make the "counter" static. This way, even when you load between scenes and what not, the number always stays.
I have edited the code without player prefs .you can check that.
O$$anonymous$$G. Thank you soo much! You guys help me alot!! Thanks again Big smiles