Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using shared preferences between unity and native android sdk

I am working on an app using native android sdk development. However I have a co-worker who is working on Unity.

I would like to create an activity A that would does some work and then call another activity 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?

Thank you so much

like image 394
Snake Avatar asked Oct 24 '25 00:10

Snake


1 Answers

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.

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)

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;
}



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 } );
}



Usage in 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");
}




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!

like image 95
Venkat at Axiom Studios Avatar answered Oct 26 '25 15:10

Venkat at Axiom Studios



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!