How to save and load a binary file in android? I am building a Unity game

I have been following “Saving and Loading Player Game Data in Unity” a tutorial by Zdravko Jakupec. My game is saving file on unity editor and in web but not doing the same in Android.
I have came across many solutions and tired them but I haven’t figured out a way yet.
I have tried writing on external memory,
Using Application.persistentdatapath instead of Application.datapath.
Using a

FileStream saveFile = File.Create(“jar:file://” + Application.dataPath + “!/save.binary”);

instead of

FileStream saveFile = File.Create(Application.dataPath + “/save.binary”);

Can anyone please help me?

I have been trying it since last week.

here is the link to that tutorial https://www.sitepoint.com/saving-and-loading-player-game-data-in-unity/

Hi,
Here I am sending the code. I’m not sure if it will work for you or not. But try with this.

public static void SaveFile(string filename, System.Object obj)
 {
     try
     {
         filename = Application.dataPath + @"\Resources\SaveLoad\" + filename;
         Stream fileStream = File.Open(filename, FileMode.Create, FileAccess.Write);
         BinaryFormatter formatter = new BinaryFormatter();
         formatter.Serialize(fileStream, obj);
         fileStream.Close();
     } 
     catch (Exception e)
     {
         Debug.LogWarning("Save.SaveFile(): Failed to serialize object to a file " + filename + " (Reason: " + e.Message + ")");
     }
 }
 
 public static System.Object LoadFile(string filename)
 {
     try
     {
         filename = Application.dataPath + @"\Resources\SaveLoad\" + filename;
         Stream fileStream = File.Open(filename, FileMode.Open, FileAccess.Read);
         BinaryFormatter formatter = new BinaryFormatter();
         System.Object obj = formatter.Deserialize(fileStream);
         fileStream.Close();
         return obj;
     } 
     catch (Exception e)
     {
         Debug.LogWarning("SaveLoad.LoadFile(): Failed to deserialize a file " + filename + " (Reason: " + e.Message + ")");
         return null;
     }       
 }

Hope this will work for you.

2 Likes

Hik kevinmartin2708, Wecome to the forums.

When including code within a post, please highlight the code then click the </> icon in the editor’s menu. That will put the code in a box with scrollbars and preserve the formatting. We would appreciate it if you would edit your post #2 and try that technique to box your code.

Thanks

Hi ronpat,

Thanks for the info. i will keep in mind in next answer.

Thanks again

1 Like

Thanks for your interest kevinmart2708.

Actually I have solved the problem. There was nothing wrong with the code. Android doesn’t deal with .binary extension, so I changed from .binary to .dat and it worked.

I was overlooking the fact that Android doesn’t save .binary.

Regards.

3 Likes

Hi,

Thanks @mhumzaawan1

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.