HELP! PlayerPrefs.HasKey doesn't work?!?

I’m using the following script to check for a PlayPrefs setting and if it doesn’t exist it will create it:

function Start () {
	if (PlayerPrefs.HasKey("MySetting") == false) {
		SetPreferences () ;
	}
}

function SetPreferences () {
	PlayerPrefs.SetInt("MySetting", 0);
}

This works fine on my Mac, the first time the application is run it creates a preferences file.

But when I run it in a Windows stand-alone nothing happens. It doesn’t create an entry in the Registry. Has anyone else run into this and how do I fix it? Does PlayerPrefs.HasKey not work under Windows? I tested this with various builds and it’s always the same!

EDIT: I’ve tested and tested and apparently PlayerPrefs.HasKey doesn’t work under Windows! I’ve filed a bug report but I really need a workaround as I am supposed to deliver this application by the end of the day… :frowning: Bah humbug… :frowning:

1 Like

What is that if statement evaluating to on Windows then? And does it evaluate to true if the key does exist?

I created a simple test project with this script:

var myText : GUIText;

function Start () {
   if (PlayerPrefs.HasKey("MySetting") == false) {
      SetPreferences ();
   }
   DisplayPrefs ();
}

function SetPreferences () {
   PlayerPrefs.SetString("MySetting", "This works!");
}

function DisplayPrefs () {
	myText.text = PlayerPrefs.GetString("MySetting");
}

In a Windows stand alone the GUIText field is empty. I just got an email from Aras that this is a known bug in 2.1. Now I need to find a work around, any suggestions?

I don’t know, how do I display error messages under Windows?

Haven’t tried that yet, but since Aras says it’s a bug I think I’m better off figuring out a way to work around this.

Edit: It appears that HasKey does nothing at all under Windows… still investigating…

Try creating a key first and then checking (so that it should return true) so that you can determine if it just doesn’t return false or if it never returns anything. I need to reinstall Windows under parallels or I would test myself.

The PlayerPrefs.Get* functions have a default value parameter. Pass in a weird default value and test for it:

if(PlayerPrefs.GetInt("somekey", -1234) == -1234)
{
  // key wasn't there
}

But really, doesn’t the default parameter solve your problem anyway (using an initial set of values if preferences were never set)?

2 Likes

@Matthew – that is solid work around and sidesteps the problem nicely.

YES!

I completely forgot about setting a default value, that’ll fix it! Thank you, thank you, thank you!! Merry Christmas Santa!!

1 Like