我有一个 Unity 游戏导出到 Android Studio 中。我有一个已保存游戏的列表,其中存储了玩家玩的每个游戏的最后一个场景。基本上存储玩家的进度。
从 Unity 到 Android Studio 播放的最后一个场景的编写效果非常好。但是,我不知道如何在Unity中从Android Studio读取。我有一个 putExtra 意图,应该将场景索引传递到 Unity,但我不知道如何。我还应该提到这个java脚本是我编写的唯一一个,这意味着我没有这里未提及的其他方法。
我在网上找到了一个代码可以做到这一点,但我不知道如何修改它,以便它可以与我的 Java 脚本一起使用。如果有人可以提供帮助,我将非常感激!
我的 Java 脚本(在 Android Studio 中):
public class MainActivity extends AppCompatActivity {
private int lastscene = 99;
Button btnstart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//gets the PlayerPrefs from Unity
SharedPreferences sharedPreferences = getSharedPreferences(getPackageName() + ".v2.playerprefs", Context.MODE_PRIVATE);
//Saves the last played scene (which is stores in the PlayerPrefs we got) in "lastscene"
lastscene = sharedPreferences.getInt("Scene",99);
//The reading from Unity works! Toasts the last played scene when you open the Android Studio app
Toast.makeText(getApplicationContext(), ""+lastscene,
Toast.LENGTH_LONG).show();
btnstart = (Button) findViewById(R.id.btnstart);
//Once you press the button, Unity should open and start playing from the last scene that we saved into Android Studio.
btnstart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, UnityPlayerActivity.class);
i.putExtra("listScene", lastscene);
startActivity(i);
}
});
}
}
我在网上找到的 C#,但不知道如何使其工作(Unity):
private void Awake ()
{
getIntentData ();
}
private bool getIntentData () {
#if (!UNITY_EDITOR && UNITY_ANDROID)
return CreatePushClass (new AndroidJavaClass ("com.unity3d.player.UnityPlayer"));
#endif
return false;
}
public bool CreatePushClass (AndroidJavaClass UnityPlayer) {
#if UNITY_ANDROID
AndroidJavaObject currentActivity = UnityPlayer.GetStatic<AndroidJavaObject> ("currentActivity");
AndroidJavaObject intent = currentActivity.Call<AndroidJavaObject> ("getIntent");
AndroidJavaObject extras = GetExtras (intent);
if (extras != null) {
string ex = GetProperty (extras, "listScene");
return true;
}
#endif
return false;
}
private AndroidJavaObject GetExtras (AndroidJavaObject intent) {
AndroidJavaObject extras = null;
try {
extras = intent.Call<AndroidJavaObject> ("getExtras");
} catch (Exception e) {
Debug.Log (e.Message);
}
return extras;
}
private string GetProperty (AndroidJavaObject extras, string name) {
string s = string.Empty;
try {
s = extras.Call<string> ("getString", name);
} catch (Exception e) {
Debug.Log (e.Message);
}
return s;
}
感谢我从哪里获取 Unity 脚本:Credit https://stackoverflow.com/questions/36098400/read-android-intent-extra-data-on-unity-app-launch/65092095#65092095