Binary
A binary serialization formatter helper for Unity
Usage
[System.Serializable]
public class PlayerData
{
public string playerName;
public int score;
public Vector3 position;
public PlayerData(string name, int score, Vector3 pos)
{
playerName = name;
this.score = score;
position = pos;
}
}
public class SerializationExample : MonoBehaviour
{
private string filePath;
IFormatter formatter;
void Start()
{
formatter = AceSerialization.GetBinaryFormatter();
filePath = Application.persistentDataPath + "/playerData.dat";
PlayerData data = new PlayerData("John", 100, new Vector3(1, 2, 3));
SerializeData(data);
PlayerData loadedData = DeserializeData();
if (loadedData != null)
{
Debug.Log("Loaded Player Name: " + loadedData.playerName);
Debug.Log("Loaded Score: " + loadedData.score);
Debug.Log("Loaded Position: " + loadedData.position);
}
}
void SerializeData(PlayerData data)
{
using (FileStream stream = new FileStream(filePath, FileMode.Create))
{
formatter.Serialize(stream, data);
}
Debug.Log("Data serialized to " + filePath);
}
PlayerData DeserializeData()
{
if (File.Exists(filePath))
{
using (FileStream stream = new FileStream(filePath, FileMode.Open))
{
return formatter.Deserialize(stream) as PlayerData;
}
}
else
{
Debug.LogWarning("Save file not found in " + filePath);
return null;
}
}
}Surrogates
UnityEngine Types
Serialization Surrogate
Last updated