PlayerPrefs.GetFloat

Hi,
what is returned if the key PlayerPrefs.GetFloat("Open levels"); does not exist?
Me needed that would to return null.

I wrote:

Object openlevels = PlayerPrefs.GetFloat("Open levels");
if (openlevels != null) {
//all needed of action
}

That is correct, or there is a standard methods?

A float cannot be null, so GetFloat will return default(float) (which is 0 if I recall correctly).

What you can do instead is pass it a number in the default value override that you know it will never be - something like

float openLevels = PlayerPrefs.GetFloat("Open levels", float.MinValue);
if (openLevels == float.MinValue){
     // assume it didn't return anything
}

It would be nice if they provided something like they do with raycasts - the function returns a bool and you “out” the value. But, alas, they do not to the best of my knowledge.

You can, however, check to see if the key exists at all:

bool hasKey = PlayerPrefs.HasKey("Open levels");

Unless you are using the same key name for multiple data types (which you can’t really anyway, and even if you could it would be incredibly poor practice) that should be perfectly accurate for things like:

if (PlayerPrefs.HasKey("Open levels")){
     float openLevels = PlayerPrefs.GetFloat("Open levels");
} else {
     // all needed of action
}

The general use case for things in the prefs is that you pass a default, as Kyle suggested. If you are asking for a pref, and you have a default in mind, then really, you just use whatever you get back. Always. In that general case, there’s not much reason to check HasKey().

Gigiwoo.

Thanks, I used a ‘HasKey’.