简体   繁体   English

从 Unity 写入 Player Prefs 并从 Android 读取 Shared Preferences 返回错误值

[英]Write on Player Prefs from Unity and read Shared Preferences from Android returns wrong value

I'm working on a game exported to我正在开发一个导出到的游戏 . I have an Activity to save values on SharedPreferences that will be retrieve from Unity Activity and updated from PlayerPrefs .我有一个Activity来保存SharedPreferences上的值,这些值将从Unity Activity检索并从PlayerPrefs更新。 Also these values will be read from SharedPreferences from the Main Activity.此外,这些值将从主活动的SharedPreferences 中读取。

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 . Main Activity 在Shared Preferences上保存一个值并启动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.Unity 中,我从PlayerPrefs获取值没有问题,但是当我更新PlayerPrefs上的首选项并返回到Main Activity 时,该值是相同的。

在此处输入图片说明 在此处输入图片说明

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.正如您所看到的,值发生了变化,但空格被替换为%20值。

在此处输入图片说明

This is my code from Unity Controller :这是我来自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.我无法弄清楚在这个过程中发生了什么,任何帮助表示赞赏。

What you may be missing is saving the changes done to Prefs by calling:您可能缺少的是通过调用保存对 Prefs 所做的更改:

PlayerPrefs.Save();

So, your code should look like:因此,您的代码应如下所示:

public void saveOnDataFromShared(string name) {
    PlayerPrefs.SetString("PlayerName", name);
    PlayerPrefs.Save();
    textShared.text = name;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM