1

I have problems with PlayerPrefs on Android. I want my tutorial to show just one time so I wrote this code:

void Awake(){
        firstTime = false;
        hasPlayed = PlayerPrefs.GetInt ("hasPlayed");
        if (hasPlayed == 0) {
            firstTime = true;
        } else {
            PlayerPrefs.SetInt ("hasPlayed", 1);
            firstTime = false;
            PlayerPrefs.Save ();
        }
}

Once built and tested on phone, the apk doesn't create any folder on /data or whatever and consequently, the tutorial is showing everytime I run the game.

Programmer
  • 121,791
  • 22
  • 236
  • 328
user1423168
  • 155
  • 1
  • 1
  • 13

1 Answers1

1

PlayerPrefs.GetInt takes another parameter you can use to return a value if the provided key does not exist. Check if hasPlayed key exist with default value of 0. If the key does not exist, it will return that default value which is 0.

If it returns 0, set hasPlayed to 1 then play your tutorial. If it returns 1, this means that the tutorial has been played before. Similar to this question, but needs a little bit of modification.

Here is what it should look like:

void Start()
 {
     //Check if hasPlayed key exist. 
     if (PlayerPrefs.GetInt("hasPlayed", 0) == 1)
     {
         hasPlayed();
     }
     else
     {
         //Set hasPlayed to true
         PlayerPrefs.SetInt("hasPlayed", 1);
         PlayerPrefs.Save();

         notPlayed();
     }
 }


 void hasPlayed()
 {
     Debug.Log("Has Played");
     //Don't do anything
 }

 void notPlayed()
 {
     Debug.Log("Not Played");
     //Play your tutorial
 }

 //Call to reset has played
 void resetHasPlayed()
 {
     PlayerPrefs.DeleteKey("hasPlayed");
 }
Community
  • 1
  • 1
Programmer
  • 121,791
  • 22
  • 236
  • 328
  • @Cabrra Yes, `PlayerPrefs.HasKey` can be used. I actually used `PlayerPrefs.GetInt` on purpose so that this can be extended more. For example, most games have different levels with a tutorial in each level. The code above above can easily be extended to check which tutorial the player last played and which one to play next by adding `else if (PlayerPrefs.GetInt("hasPlayed", 0) == 2)`. You can add as many tutorials as possible. `PlayerPrefs.HasKey` can't do this alone and will still require `PlayerPrefs.GetInt` in combination with it which makes code longer. – Programmer Jul 27 '16 at 19:51
  • Also `GetInt(string key, int defaultValue);` performs `PlayerPrefs.HasKey` in the hood. it shortens the code. `PlayerPrefs.HasKey` is only needed if you just want to know if the key exist. In my case, I want to know if it exist and also get the value without using two functions. – Programmer Jul 27 '16 at 19:54
  • 1
    Perfect, this statement: PlayerPrefs.GetInt("hasPlayed", 0) == 1 did the trick. Thanks a lot! – user1423168 Jul 27 '16 at 20:33