Question by
GameDeveloperAf · May 03, 2021 at 09:00 PM ·
saveloadbinaryformatterbinaryfilestream
How to add a new data to existing Binary file without erase the previous data?
Hi there, I save my meshes data using Binary format. I can save and load using Binary format. But I saw there a little issue in saving step. I can save then load it back. But when I launch the game and I add new variables into "MeshData" class and I save it then when I load and I see that my previous data erased in the saved file. Because the file is overwriting into existing file.
SHORTLY:
Saving the File Without Deleting What's Already There. I do not want to overwrite the whole file. I just want to add a new line/data into existing file without erase the previous data. How to add a new data into existing Binary file?
Code to SAVE and LOAD Mesh Data:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
[System.Serializable]
public class MeshData
{
public List<float> vertices;
public List<float> uvs;
public List<float> normals;
public List<int> triangles;
}
[System.Serializable]
public class MeshDatabase
{
public MeshData[] meshDatas;
}
public class GetMeshData : MonoBehaviour
{
public MeshData[] meshDatas;
public MeshDatabase meshDatabase;
public BinaryFormatter binaryFormatter;
public FileStream fileStream;
void Update()
{
if (Input.GetKeyDown(KeyCode.S))
{
Save();
Debug.Log("SAVED");
}
if (Input.GetKeyDown(KeyCode.L))
{
Load();
Debug.Log("LOADED");
}
}
public void Save()
{
binaryFormatter = new BinaryFormatter();
fileStream = File.Create(Application.dataPath + "/StreamingAssets/Mesh.dat");
binaryFormatter.Serialize(fileStream, meshDatabase);
fileStream.Close();
}
public void Load()
{
if (File.Exists(Application.dataPath + "/StreamingAssets/Data.dat"))
{
binaryFormatter = new BinaryFormatter();
fileStream = File.Open(Application.dataPath + "/StreamingAssets/Mesh.dat", FileMode.Open);
meshDatabase = (MeshDatabase)binaryFormatter.Deserialize(fileStream);
fileStream.Close();
}
}
}
PLEASE EXPLAIN AS CODE!!! THANKS.
Comment