I recently discovered that Unity refuses to save an int larger than 2,147,483,647 in PlayerPrefs.
The reason why this occurs is well-documented
, but what is a workaround for this problem?
I need to store a number that can become incredibly large - indeed, larger than two billion - in PlayerPrefs. How would I go about doing this?
You could use the technique in
ArrayPrefs2
, namely converting the bytes of the long to a base64 string. This has the advantage of obfuscating the actual value to some extent, if you care about that, as well as being somewhat more compact than a straight ToString() conversion for very large numbers (but less compact for small numbers).
function Start () {
var x : long = 123456789123456;
SetLong("foo", x);
var y = GetLong("foo");
Debug.Log (y);
function SetLong (key : String, x : long) {
var bytes = System.BitConverter.GetBytes(x);
PlayerPrefs.SetString(key, System.Convert.ToBase64String(bytes));
function GetLong (key : String) : long {
var bytes = System.Convert.FromBase64String(PlayerPrefs.GetString(key));
return System.BitConverter.ToInt64(bytes, 0);