API SaveContentWriter - shmellyorc/Box GitHub Wiki
Namespace: Box.Saves
SaveContentWriter extends BinaryWriter to offer high-level, type-safe serialization methods for writing common game data structures—such as Vect2
, Rect2
, Color
, Enums
via Write(Enum)
, and arbitrary objects via DataContractSerializer
—directly to a binary stream. It merges low-level binary writing with structured data serialization, simplifying the process of saving custom file formats in your application.
Instances are created internally via SaveTypeWriterReader
; the constructor is internal and not publicly exposed.
Property | Description |
---|---|
None | This class provides no additional public properties beyond those inherited from BinaryWriter. |
Method Signature | Description | Returns |
---|---|---|
void Write(Vect2 value) |
Writes the two float components (X and Y) of a Vect2 to the stream. | void |
void Write(Rect2 value) |
Writes the four integer components (X, Y, Width, Height) of a Rect2. | void |
void Write(BoxColor value) |
Writes the four integer channels (Red, Green, Blue, Alpha) of a BoxColor. | void |
void Write(Enum value) |
Converts the enum to a single byte and writes it, enabling compact enumeration storage. | void |
void WriteObject(object value) |
Serializes the object using DataContractSerializer into a binary XML payload, writes its length (int), then the raw byte buffer. | void |
// Define a data type to save
public class PlayerData
{
public Vect2 Position { get; set; }
public Color Color { get; set; }
public Item Item { get; set; }
}
public class Item
{
public string Name { get; set; }
public int Damage { get;set; }
}
// Implement a concrete handler
public class PlayerDataHandler : SaveTypeWriterReader<PlayerData>
{
protected override void Save(SaveContentWriter writer, PlayerData value)
{
writer.Write(value.Position);
writer.Write(value.Color);
writer.Write(value.Item)
}
protected override PlayerData Load(SaveContentReader reader)
{
Vect2 position = reader.ReadVect2();
Color color = reader.ReadColor();
Item item = reader.ReadObject<Item>();
return new PlayerData() { Level = level, Name = name, Item = item };
}
}
// Usage
var handler = new PlayerDataHandler();
var player = new PlayerData
{
Level = 5,
Name = "Avery",
Item = new Item() { Name = "Long Sword", Damage = 4 }
};
// Save (auto-compress if beneficial)
handler.Save("save1.bin", player);
// Load (auto-decompress if needed)
PlayerData loaded = handler.Load("save1.bin");
Console.WriteLine($"Level: {loaded.Level}, Name: {loaded.Name}");