在unity和本机android sdk之间使用共享的首选项 [英] Using shared preferences between unity and native android sdk
问题描述
我正在使用本地android sdk开发的应用程序上工作.但是我有一个在Unity上工作的同事.
I am working on an app using native android sdk development. However I have a co-worker who is working on Unity.
我想创建一个可以完成一些工作的活动A,然后调用另一个活动B.
I would like to create an activity A that would does some work and then call another activity B.
我的同事正在使用Unity创建活动B屏幕.
My coworker is creating Activity B screen using Unity.
这两个活动都将使用共享的首选项(对其进行读写)
Both activities will be using shared preferences (reading and writing to it)
有没有办法做到这一点?
Is there way that this can be accomplished?
非常感谢您
推荐答案
您需要为Android编写一个插件才能使其正常工作.虽然正式文档非常适合入门,但是这里有一些示例代码,您可以在阅读完之后使用.
You'd need to write a plugin for Android to get this to work. While the official doc is great to get started, here's some sample code you can use after you've gone through it.
我不会详细介绍如何创建插件,因为在Unity网站上有很好的记录(nexx给出的链接)
I won't go into details about how to create the plugin, because that's pretty well documented on the Unity website (link given by nexx)
在下面的示例中,我仅编写了两种方法.您可以修改它们以接受并返回其他数据类型,或者更好地使它们通用.
本地Android代码
In the below example, I've just written a couple of methods. You can modify them to accept and return other data types, or better make them generic.
Native Android Code
public static final String PREFS_NAME = "MyPrefsFile";
public void setPreferenceString (String prefKey, String prefValue) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(prefKey, prefValue);
editor.commit();
}
public String getPreferenceString (String prefKey) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String playerName = settings.getString(prefKey, "");
return playerName;
}
现在,在 Unity C#端,您的插件将具有这样的代码
Now, on Unity C# side, your plugin will have code like this
AndroidJavaObject AJO = null;
public void SetPreferenceString (string prefKey, string prefValue) {
if(AJO == null)
AJO = new AndroidJavaObject("com.yourcompany.productname.activity", new object[0]);
AJO.Call("setPreferenceString", new object[] { prefKey, prefValue } );
}
public string GetPreferenceString (string prefKey) {
if(AJO == null)
AJO = new AndroidJavaObject("com.yourcompany.productname.activity", new object[0]);
if(AJO == null)
return string.Empty;
return AJO.Call<string>("getPreferenceString", new object[] { prefKey } );
}
在Unity中的用法
//Setting a player's name to be "John Doe"
void Start () {
SetPreferenceString("playerName", "John Doe");
}
//Get the stored player's name
string GetPlayerName () {
return GetPreferenceString("playerName");
}
这绝不是编写插件的最佳方法.但是,它应该为您提供一个如何处理SharedPrefs的思路.
This is by no means the best way of writing the plugin. It should, however give you a fair idea how to handle SharedPrefs.
显然,请确保两个人都使用相同的首选项!
Obviously, ensure that both of you are using the same preferences!
这篇关于在unity和本机android sdk之间使用共享的首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!