- Home /
Save script not saving data on android device
I have found an issue with my game, due to the fact that my script (working fine on pc) doesn't work on android. I've checked to see where the data was being saved, and found out it wasn't being saved. I've looked up a tutorial for android, that didn't seem to work either. So sorry I keep posting here :/
Here's the code:
using UnityEngine; using System.Collections; using System.IO; using System.Runtime.Serialization.Formatters.Binary;
public class SaveManager1 : MonoBehaviour {
public GameObject CM1;
public BuildClick1 M1;
public GameObject CM2;
public GoldPerSec M2;
public float GPS;
//public GameObject CM3;
//public BuildClick1 M3;
//public float CurrentHp;
// Use this for initialization
void Start () {
//GPS = M2.tick;
M1 = CM1.GetComponent<BuildClick1> ();
M2 = CM2.GetComponent<GoldPerSec> ();
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.O)){
Save ();
//CurrentHp = HP1.CurrentHp;
}
if(Input.GetKeyDown(KeyCode.P)){
Load ();
}
}
public void Save()
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (FileStream fs = new FileStream("sv1.bnxt", FileMode.Create, FileAccess.Write))
{
binaryFormatter.Serialize(fs, M1.gold);
binaryFormatter.Serialize(fs, M1.goldperclick);
binaryFormatter.Serialize(fs, M2.GPS);
}
}
public void Load()
{
if (!File.Exists("sv1.bnxt"))
return;
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (FileStream fs = new FileStream("sv1.bnxt", FileMode.Open, FileAccess.Read))
{
M1.gold = (float)binaryFormatter.Deserialize(fs);
M1.goldperclick = (int)binaryFormatter.Deserialize(fs);
//float goldPerSecond = (float)binaryFormatter.Deserialize(fs);
//M2.GetGoldPerSec (goldPerSecond);
M2.GPS = (float)binaryFormatter.Deserialize(fs);
}
}
}
Thanks for taking time to read this post, if you know what the answer to this question is, please post it! Thank you.
Answer by tmalhassan · Sep 16, 2017 at 04:37 PM
To save data on mobile phones, you can use playerPrefs this will work on all platforms.
Read more about it here: https://docs.unity3d.com/ScriptReference/PlayerPrefs.html
Watch this detailed tutorial on how to implement it: https://www.youtube.com/watch?v=LBs6qOgCDOY&t=368s
or watch this one: https://www.youtube.com/watch?v=HyPeZSSKx4M
All the best :)
Ah thanks, sorry that I couldn't reply right away, computer was being slow :/