- Home /
How to use PlayerPrefs?
Hi guys.
How can i use PlayerPrefs to save my game? Is there any tutorial available out there (JavaScript) ? If not, can someone give me an example on how to use it?
Here is a piece of my code:
Unlocking level code:
static var level2unlock : boolean;
var level2 : UIButton;
function Update () {
if(!level2unlock)
{
level2.controlIsEnabled = false;
}
else
{
level2.controlIsEnabled = true;
}
}
Code used in level 1. If a condition is met, unlock level 2.
if (transform.position.y > 47)
{
levelunlock.level2unlock = true;
}
I know that i must use PlayerPrefsX to save this kind of information, but i haven't used PlayerPrefs before so i still have no idea. Anyone can help me?
Thanks
Answer by Skjalg · Mar 17, 2011 at 11:32 AM
Since a boolean value is just 0 or 1, then you can use:
SetInt Sets the value of the preference identified by key.
GetInt Returns the value corresponding to key in the preference file if it exists.
So when you do:
static var level2unlock : int = PlayerPrefs.GetInt("Level2Unlock", 0);
then in your function you do
if(level2unlock == 1)
{
level2.controlIsEnabled = true;
}
else
{
level2.controlIsEnabled = false;
}
PlayerPrefs.SetInt("Level2Unlock", (level2.controlIsEnabled ? 1 : 0));
PS: Code needs to be adapted, since I normally program in c# and this was done in the answer box here :)
Hey.. Thanks for your answer :D I edited the code like the above, however, when i hit play, the level 2 is unlocked already :-/ What should i change? :)
The thing with PlayerPrefs is that it stores the values in the registry so that the next time you open your game it will also be unlocked.
So basically, once you've unlocked something it will stay unlocked forever. One way around this problem is to have the player type in a name for himself, then when you store something you do PlayerName + "Level2Unlock" in the GetInt method..
Answer by O-R-C · Feb 19, 2014 at 01:47 AM
You could write a script that say "when get button reset PlayerPrefs" for instance.
if(Input.GetKey(KeyCode.B))
{
PlayerPrefs.SetInt("Level2Unlock", 0);
}
this will reset you playerprefs I think. You will have to remove this code when you finnish your game though.
Your answer
Follow this Question
Related Questions
Check the size of PlayerPrefs from web player 2 Answers
PlayerPrefs save after quit? 2 Answers
loop through playerprefs ints and find specific one 2 Answers
Audio not playing on TriggerEnter (Pic Included) 3 Answers
UI Slider, Save Values and Change Them 0 Answers