我使用以下代码统一设置首选项值
rightJointPos = rightJoint.localPosition;
PlayerPrefs.SetFloat ("rigX", rightJointPos.x);
PlayerPrefs.SetFloat ("rigY", rightJointPos.y);
PlayerPrefs.SetFloat ("rigZ", rightJointPos.z);
PlayerPrefs.Save ();
我使用以下代码在android中获取值。
SharedPreferences settings = getApplicationContext().getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
float rigX=settings.getFloat("rigX", 0.0f);
float rigY=settings.getFloat("rigY", 0.0f);
float rigZ=settings.getFloat("rigZ", 0.0f);
Toast.makeText(getApplicationContext(),"start 11 "+rigX+ ":"+rigY+":"+rigZ, 400).show();
我在烤面包上打印此值。总是得到0.0值而不是实际值。
如何在Android中获得此值?
请帮助我解决此问题。此代码缺少什么?
提前致谢
最佳答案
Android的SharedPreferences
和Unity的PlayerPrefs
是完全不同的数据存储API,具有不同的实现,并且两者不可互换。
如果使用PlayerPrefs.SetFloat
保存,则必须使用PlayerPrefs.GetFloat
阅读
float rigX = PlayerPrefs.GetFloat("rigX", 0.0f);
float rigY = PlayerPrefs.GetFloat("rigY", 0.0f);
float rigZ = PlayerPrefs.GetFloat("rigZ", 0.0f);
如果要从Java进行此调用,并且需要阅读
PlayerPrefs
,则必须使用UnityPlayer.UnitySendMessage
来获取这些PlayerPrefs
值。由于UnityPlayer.UnitySendMessage
无法返回值,因此您需要在其上包装一个包装。C#:
class SettingsReader : MonoBehaviour
{
//Sends the data from PlayerPrefs to the receiveResult function in Java
void sendResultToJava(float value)
{
AndroidJavaClass javaPlugin = new AndroidJavaClass("com.company.product.MyPlugin");
javaPlugin.Call("receiveResult", new object[] { value.ToString() } );
}
//Called from Java to get the saved PlayerPrefs
void getValue(string key)
{
float value = PlayerPrefs.GetFloat(key) //Get the saved value from key
sendResultToJava(value); //Send the value to Java
}
}
Java:
封装:com.company.product.MyPlugin
public final class MyPlugin
{
string result = "";
//Gets saved value
float getSavedValue(string key)
{
//Calls Unity function "getValue" from a script attached to GameObject named GameObjectName then pass in the key
UnityPlayer.UnitySendMessage("GameObjectName", "getValue", key);
return Float.parseFloat(result);
}
//Receives result from C# and saves it to result variable
void receiveResult(string value)
{
result = "";//Clear old data
result = value; //Get new one
}
}
从Java方面的用法:
float rigX = getSavedValue("rigX");
float rigY = getSavedValue("rigY");
float rigZ = getSavedValue("rigZ");