PS: I’ve deleted the PlayerPref at start to test things and so I KNOW it returns null, there’s just no function I can find to determine whether it’s null.
when you “get” the value to display on the highscore, if that parameter doesn’t exisist, it will use the default parameter. Which you can set as highscore.
Fair enough, and that is what the API promises, but obviously not what it delivers.
Even as far back as Unity5, supplying a default null to GetString() will give you in fact an empty string if the key in question doesn’t exist.
Before you get too exercised, note that:
a) yes it is annoying because it’s not what the API promises
b) once identified it can be trivially worked around
c) non-null default strings still work precisely as expected
d) Unity is unlikely to change it because it would probably break their own internal stuff
e) this behavior is analogous to a public / serializable string field in a MonoBehaviour/ScriptableObject that you never fill out before serializing. Hint: that won’t be null either, EXCEPT in the case that it is a new never-before-serialized field.
Warts are warts. Show me an API without warts. We know about this wart, as engineers we can deal with it.
And how do you propose to distinguish if you didn’t pass a second parameter or if you pass null into it? I’m genuinely curious. Because that’s the problem.
// Returns the value corresponding to /key/ in the preference file if it exists.
public extern static string GetString(string key, string defaultValue);
public static string GetString(string key)
{
return GetString(key, "");
}
But this is secondary, the interesting question is the C++ side. Obviously we only can guess, but most likely the string becomes an std:string (which is null-terminated and cannot be null) because of the variable length.
So I think you end up with an empty string with a null-terminator in it. And then in case of the missing key you get back the empty string which becomes an empty managed string after marshalling. And the second definition of the GetString with the empty string second parameter gives the hint in to this direction.
But again, it’s an educated guess since we don’t have the source code for the other side.