- Home /
player prefs, problem but no problem???
i finally got player prefs to work, but unity insists that there is a problem, actually three. I made it so it saves the value of a variable, gold. it works, but it says a bunch of wierd problems. Heres the script with the gold variable:
function Start() { if(!PlayerPrefs.HasKey("Gold")) { static var gold : int = 0; PrefsScript.saveIntPref("Gold",gold); } else { PrefsScript.loadIntPref("Gold",gold); } }
function OnGUI() { GUI.Label(Rect(1300,20,100,50), "Gold: " + PlayerPrefs.GetInt("Gold")); if (GUI.Button(Rect(5,80,80,50), "Pause")) {
if(Time.timeScale > 0)
{
Time.timeScale = 0;
}
else
{
Time.timeScale = 1;
}
}
if (GUI.Button(Rect(5,15,80,50), "Main Menu"))
{
Application.LoadLevel(0);
}
} function Update() { PrefsScript.saveIntPref("Gold",gold); }
and here's the script with the PlayerPrefs functions:
static function saveIntPref(key,variable)
{
PlayerPrefs.SetInt(key,variable);
}
static function loadIntPref(key,variable)
{
variable = PlayerPrefs.GetInt(key);
}
static function saveFloatPref(key,variable)
{
PlayerPrefs.SetFloat(key,variable);
}
static function loadFloatPref(key,variable)
{
variable = PlayerPrefs.GetFloat(key);
}
static function saveStringPref(key,variable)
{
PlayerPrefs.SetString(key,variable);
}
static function loadStringPref(key,variable)
{
variable = PlayerPrefs.GetString(key);
}
static function killPref(key)
{
PlayerPrefs.DeleteKey(key);
}
Answer by Eric5h5 · May 23, 2010 at 05:09 AM
You do have several problems. For one, you're declaring the "gold" variable in Start, which makes it local to Start only, rather than global. Also you can't declare local variables as static, not that you want "gold" to be local anyway.
Also, you're doing PlayerPrefs.GetInt every frame in OnGUI, which is not a good idea at all. Just do it once when you need to load it, not every frame. Likewise, saving using PlayerPrefs every frame in Update is an even worse idea. Again, just do it once when needed.
Finally, your "saveIntPref" functions and so on don't really make any sense to me. Why not just use PlayerPrefs directly? I don't see what you're trying to gain by doing it that way.
Your answer
Follow this Question
Related Questions
playerprefs problem 0 Answers
Save and load data with Javascript... 0 Answers
Saving and Loading an Object and it's Children in Javascript 2 Answers
Save/Load Variable with playerprefs 1 Answer
Set int to object from list? 0 Answers