Skip to content

Instantly share code, notes, and snippets.

@openroomxyz
Created April 21, 2020 12:19
Show Gist options
  • Save openroomxyz/d7c57a630ad8feab36d44e5908e79f35 to your computer and use it in GitHub Desktop.
Save openroomxyz/d7c57a630ad8feab36d44e5908e79f35 to your computer and use it in GitHub Desktop.
Unity : How to save game data in bin format at runtime by serializing objects ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class SaveSystem
{
public static void Save(StoringDataInBinary d)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/player.fun";
FileStream stream = new FileStream(path, FileMode.Create);
StoreDataExample data = new StoreDataExample(d);
formatter.Serialize(stream, data);
stream.Close();
}
public static StoreDataExample Load()
{
string path = Application.persistentDataPath + "/player.fun";
if(File.Exists(path))
{
BinaryFormatter formater = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
StoreDataExample data = formater.Deserialize(stream) as StoreDataExample;
stream.Close();
return data;
}
else
{
Debug.LogError("MY Save file not found in " + path);
return null;
}
}
}
[System.Serializable]
public class StoreDataExample
{
public int level;
public int health;
public float[] position;
public float[] rotation;
public StoreDataExample(StoringDataInBinary stb)
{
level = stb.level;
health = stb.healt;
position = new float[3];
position[0] = stb.transform.position.x;
position[1] = stb.transform.position.y;
position[2] = stb.transform.position.z;
rotation = new float[3];
rotation[0] = stb.transform.localEulerAngles.x;
rotation[1] = stb.transform.localEulerAngles.y;
rotation[2] = stb.transform.localEulerAngles.z;
}
}
public class StoringDataInBinary : MonoBehaviour
{
public int level;
public int healt;
// Start is called before the first frame update
void Start()
{
Debug.Log("Files saved at!");
Debug.Log(Application.persistentDataPath);
Load();
}
private void Load()
{
StoreDataExample ex = SaveSystem.Load();
if (ex != null)
{
transform.position = new Vector3(ex.position[0], ex.position[1], ex.position[2]);
transform.localEulerAngles = new Vector3(ex.rotation[0], ex.rotation[1], ex.rotation[2]);
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.V))
{
SaveSystem.Save(this);
}
if (Input.GetKey(KeyCode.B))
{
Load();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment