Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Double with PlayerPrefs?

In one of my projects I originally started using floats, but after a bit I realized that its precision isn't exactly how I want it to be. I have automated system that adds value of X coins every second, and given that that float is at big number (more than 2 million), it just do not add such small value to it anymore.

So my next call was to use double instead of float. After changing everything from float to double, I realized that I store values in PlayerPrefs, in which I guess I cannot store doubles? So now I'm a bit confused.

How do I pull out existing float information from PlayerPrefs and put that floats value in double, and then save that double value in PlayerPrefs? A bit confusing for me, so I'm seeking help.

Here's part of my code:

// old
// public float totalP;

// new    
public double totalP;

void OnEnable()
{

    if (!PlayerPrefs.HasKey ("game_totalP")) 
    {
        PlayerPrefs.SetFloat ("game_totalP", totalP);
    } 
    else 
    {
        totalP = PlayerPrefs.GetFloat ("game_totalP");
    }        
}

Any help would be appreciated!

like image 900
Arthur Belkin Avatar asked Jun 16 '26 17:06

Arthur Belkin


1 Answers

You can encode the double as two int and store and retrieve those.

To store:

var storeBytes = BitConverter.GetBytes(totalP);
var storeIntLow = BitConverter.ToInt32(storeBytes, 0);
var storeIntHigh = BitConverter.ToInt32(storeBytes, 4);
PlayerPrefs.SetInt("game_totalP_low", storeIntLow);
PlayerPrefs.SetInt("game_totalP_high", storeIntHigh);

To retrieve:

var retrieveBytes = new byte[8];
Array.Copy(BitConverter.GetBytes(storeIntLow), retrieveBytes, 4);
Array.Copy(BitConverter.GetBytes(storeIntHigh), 0, retrieveBytes, 4, 4);
totalP = BitConverter.ToDouble(retrieveBytes, 0);
like image 170
jdphenix Avatar answered Jun 19 '26 08:06

jdphenix