Ryan Cat
Ryan Cat

Reputation: 25

using Playerprefs on Android Mobile Platform for unity

I have a question about playerprefs on my android mobile game not initializing properly. I have already pre-set my playerprefs data on a variable with a value of 3. In my play mode on unity the value is showing 3 through the textmesh that I have it scripted on. But when I install and test it on my android mobile device it is 0. can someone help how to properly initialize my playerprefs data to the right value on android platform?


public static Game GM;
int maxAntiBody;
public TextMeshProUGUI antibodyTexMesh;

void Start () {
if (GM == null)
{
    GM = this;
}
maxAntiBody = PlayerPrefs.GetInt("MaxAntiBody");
antibodyTexMesh.text = maxAntibody.toString();
}

void Update () {
 debugging();
}

 //I use this method for setting or resetting my desired value for the 
playerprefs data I'm working with. In this case I choose 3 as a value.

void debugging() {
if (Input.GetKeyDown(KeyCode.M))
{

    PlayerPrefs.SetInt("MaxAntiBody", plus++);
    Debug.Log("max anti body value is : " + 
 PlayerPrefs.GetInt("MaxAntiBody"));
}
else if (Input.GetKeyDown(KeyCode.R))
{
    plus = 0;
    PlayerPrefs.SetInt("MaxAntiBody", plus);
    Debug.Log("max anti body is now reseted to : " + 
  PlayerPrefs.GetInt("MaxAntiBody"));
}
}

Upvotes: 1

Views: 910

Answers (1)

sommmen
sommmen

Reputation: 7648

You're only ever setting the playerpreference when you press the M or R key (in your debugging method).

if you want the value to have a default value you should add it to your Start();

Something like;

void Start()
{

    // Set the MAxAntiBody to 3 if the value was never set to an initial value
    if(PlayerPrefs.GetInt("MaxAntiBody") == default(int))        
        PlayerPrefs.SetInt("MaxAntiBody", 3);

    ...

}

EDIT: as pointed out in the comments you could also do the following:

var x = PlayerPrefs.GetInt("MaxAntiBody", 3);

Returns the value corresponding to key in the preference file if it exists. If it doesn't exist, it will return defaultValue.

Do not that the first piece of code actually creates the key if GetInt() returns the default value (0) - but the second sample may not. This depends on the implementation of GetInt(string, int) - and i'm not sure if that creates the key if it does not exist.

Upvotes: 1

Related Questions