- Home /
200MB file save causing unity memory to increase by over a gigabyte
Why is it that this line of code to save a 200MB sized object causes unity in memory to increase over 1GB? Before running this, unity memory usage sits at about 800MB while running my game within the editor. As soon as I serialize and save the game data, the memory usage skyrockets. I've verified there is literally only 200MB being saved to the file but when unity memory usage gets this high, it's prone to crash. I see no reason why memory usage would increase so much, the stream is disposed and closed. It is redundant for me to even use stream.dispose because close disposes it but just wanted to double check.
File Manager Class:
public void WriteStream(string saveLocation, object o)
{
FileStream fs = new FileStream(saveLocation, FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, o);
fs.Close();
}
From another class:
FileManager fm = new FileManager();
for(int i = 0; i < tileData.Length; i++)
{
string path = appDataFolder + @"\"+levelName+"layer"+i.ToString()+".dat";
fm.WriteStream(path, tileData[i]);
}
Serializable object that is being saved (tileData above):
[Serializable]
public class TileMapData : ISerializable
{
public int layer;
public int width;
public int height;
public int[,] type;
public int[,] bitmask;
public int[,] status;
public int[,] groupID;
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
//omitted to save space
}
public TileMapData(SerializationInfo info, StreamingContext context)
{
//omitted to save space
}
}
What would be a way to overcome this problem?
Second attempt using StreamWriter this time, still same problem.
public void BinaryWriteSave(string saveLocation, object o)
{
byte[] byteArray = ObjectToByteArray(o);
using (BinaryWriter bw = new BinaryWriter(File.Open(saveLocation, FileMode.Create)))
{
bw.Write(byteArray);
}
}
What's the object?
Also, bear in $$anonymous$$d that memory allocated isn't necessarily memory used.
Without a reproducible example, this question is a moot point. You're excluding the exact information that would be necessary for useful discussion.
Answer by smoggach · Aug 14, 2014 at 09:45 PM
It depends on your object. Unity tends to load assets into memory before serializing. I'm guessing your object depends on some uncompressed textures or you've run into a dependency issue.
I think it's a dependency issue or due to the state of your object. I've heard some people run into a situation where unity thinks their object depends on every asset.
$$anonymous$$aybe some part or parts of your object needs to be uncompressed in memory before being serialized. This is the only reasons I can think of. I've only encountered this kind of behavior working with large amounts of textures.