- Home /
If PlayerPrefs.GetFloat("name") don't excist
quoted from unity scripting API for PlayerPrefs.GetFloat("keyname"):
Returns the value corresponding to key in the preference file if it exists. If it doesn't exist, it will return defaultValue.
Now I looked up the default value of a float, which should be 0.0f. But the folowing function doesn't return true:
//function in class named SaveOpenData
public static float GetPerkCost(string name)
{
return PlayerPrefs.GetFloat (name + "PerkCost");
}
//check statement
if(SaveOpenData.GetPerkCost(name) == 0.0f)
{
Debug.Log("Empty");
}
before the if statement I do:
PlayerPrefs.DeleteAll();
I also tried to compare it with null or just 0. What am I doing wrong
Answer by LMan · Jun 07, 2014 at 05:11 PM
I believe you are looking for PlayerPrefs.HasKey!
Woa, overlooked this... I always make things more complicated... Thanks!
Answer by Eric5h5 · Jun 07, 2014 at 05:22 PM
You need to supply a default value. It's not about what the default for a float is:
PlayerPrefs.GetFloat (name + "PerkCost", 0.0f);
That way the default will be 0.0 if the PlayerPrefs entry doesn't exist, and saves having to write extra code with HasKey and so on.
Oh. They don't mention that in the API...(well not that I know.) Thanks for the comment, always happy to learn!
Yes, it's mentioned in the API docs. You quoted it yourself: "Returns the value corresponding to key in the preference file if it exists. If it doesn't exist, it will return defaultValue." That has nothing to do with the default value of floats in general; not sure why you'd interpret it that way since defaultValue is written like that to specifically refer to defaultValue in the parameter list:
static function GetFloat(key: string, defaultValue: float = 0.0F): float;
Answer by elenzil · Jan 27 at 06:02 PM
The unity docs here are incomplete, if you ask me. They seem to not describe the first flavor of the routine.
However, my tests don't match the OP's results. For me, the following code shows that the first flavor of GetFloat() returns 0 if the key is not found:
var noSuchKey = System.Guid.NewGuid().ToString();
float f = PlayerPrefs.GetFloat(noSuchKey);
Debug.Log($"PlayerPrefs['{noSuchKey}'] = {f}");