Write on Player Prefs from Unity and read Shared Preferences from Android returns wrong value
I'm working on a Unity game exported to Android. I have an Activity to save values on SharedPreferences that will be retrieve from Unity Activity and updated from PlayerPrefs. Also these values will be read from SharedPreferences from the Main Activity.
The values that I get not match with the values that I write on the main activity and only reads when I close the entire application.
Here is my code and how actually works.
The Main Activity save a value on Shared Preferences and launch the UnityPlayerActivity.
public void writeOnSharedAndLaunch(String text) {
String sharedPreferenceName = context.getPackageName() + ".v2.playerprefs";
SharedPreferences sharedPreferences = context.getSharedPreferences(sharedPreferenceName, MODE_PRIVATE);;
Editor editor = sharedPreferences.edit();
editor.putString("PlayerName", playerText.getText().toString());
editor.apply();
Intent intent = new Intent(context, UnityPlayerActivity.class);
startActivity(intent);
}
From Unity I get the value from PlayerPrefs without problems, but when I update the preference on PlayerPrefs and return to Main Activity the value is the same.
I completely close the application and I open it again.
And as you can see the value changes but the spaces are replaced with %20 value.
This is my code from Unity Controller:
public void saveOnDataFromShared(string name) {
PlayerPrefs.SetString("PlayerName", name);
textShared.text = name;
}
public void loadStringFromPlayerPrefs() {
textShared.text = PlayerPrefs.GetString ("PlayerName", "Default value");
}
I can't figure it out what happen on the process, any help is appreciated.
Help!
How can another native android app write values to my Unity PlayerPrefs? I guess in android this preferences files are all stored as SharedPreferences.
I did this within iOS but no clue on how to do this in Android!
Can someone elaborate how can I get similar thing as this?
Thank's!
Answer by liortal · Jul 26, 2016 at 04:30 AM
PlayerPrefs stores its data in a file - as you already know on Android it uses SharedPreferences.
When saving values, Unity doesn't automatically write the changrs back to file. They are kept in memory until you "flush" them by calling PlayerPrefs.Save
This is called automatically when you quit the game, so what you described makes sense.
Thanks for the answer, I didn't notice this function in the documentation.