Skip to content

Serializing Entities

Thiago edited this page Jun 3, 2024 · 2 revisions

Almost every entity in Basalt can be serialized, with a few exceptions like CameraController in Basalt.Raylib. The engine uses Newtonsoft.Json to serialize every entity to a json format and, due to how components have to be loaded with their parent entity referenced, it serializes and deserializes them manually one at a time (See Entity.SerializeToJson() and Entity.DeserializeFromJson())

Serializing and Deserializing Entities

var json = myEntity.SerializeToJson();
File.WriteAllText("./resources/myEntity.json", json );

var jsonRead = File.ReadAllText("./resources/myEntity.json");
var resultEntity = Entity.DeserializeFromJson(jsonRead);

Engine.CreateEntity(resultEntity);

Serializing Entity References

Serializing and Deserializing entity references is a bit trickier. Say you have a Target entity in your component that you want serialized. The easiest way would be to have a TargetId field and serialize that instead. To do this make sure the target entity always has a consistent Id, since by default it'll have a random GUID. After that field is properly serialized. It is as simple as finding it during OnStart()

[JsonProperty("TargetId")]
public string TargetId { get; set; }

[JsonIgnore]
private Entity? target;

public override void OnStart()
{
    if (Target == null)
    {
        Target = Engine.Instance.EntityManager.GetEntities().Find(e => e.Id == TargetId);
    }
}

This will not instantiate the desired Target entity, instead you'll need to instantiate it beforehand.