Confusion around serializing SharedComponentData

I’m trying to figure out how to serialize a world that has shared components and I’m running into issues. The shared components do not appear to be serializing. Below a test case that tries to get it to work and I’m unsure of what I’m doing incorrectly.

public struct SharedData : ISharedComponentData
{
    public int value;
}

[Test]
public unsafe void TestSharedDataSerialization()
{
    World world = new World("World 1");

    Entity entity = world.EntityManager.CreateEntity(
        world.EntityManager.CreateArchetype(typeof(TestComponentFloat)));
   
    SharedData data = default;
    data.value = 10;
   
    world.EntityManager.AddSharedComponentData(entity, data);
    Assert.IsTrue(world.EntityManager.GetSharedComponentData<SharedData>(entity).value == 10);
   
    // Needing, the apparent need, two writers to so that I can read in the reverse order seems odd
    MemoryBinaryWriter writer1 = new MemoryBinaryWriter();
    MemoryBinaryWriter writer2 = new MemoryBinaryWriter();
   
    SerializeUtility.SerializeWorld(world.EntityManager, writer1, out int[] sc);
   
    SerializeUtility.SerializeSharedComponents(world.EntityManager, writer2, sc);
   
    MemoryBinaryReader reader1 = new MemoryBinaryReader(writer1.Data);
    MemoryBinaryReader reader2 = new MemoryBinaryReader(writer2.Data);
   
    World world2 = new World("World 2");

    // It appears I have to do shared comps first (reverse order) or the length in the deserialize world
    // fails
    SerializeUtility.DeserializeSharedComponents(world2.EntityManager, reader2);
       
    ExclusiveEntityTransaction transaction = world2.EntityManager.BeginExclusiveEntityTransaction();
   
    SerializeUtility.DeserializeWorld(transaction, reader1, sc.Length);
   
    world2.EntityManager.EndExclusiveEntityTransaction();

    NativeArray<Entity> entities = world2.EntityManager.GetAllEntities(Allocator.Temp);
   
    Assert.IsTrue(world2.EntityManager.HasComponent<SharedData>(entities[0]));
   
    // Test below fails with value equal to 0
    Assert.IsTrue(world2.EntityManager.GetSharedComponentData<SharedData>(entities[0]).value == 10);
   
    entities.Dispose();
    writer1.Dispose();
    writer2.Dispose();
    world.Dispose();
    world2.Dispose();
}

What version of entities are you using? I don’t even see SerializeSharedComponents method

0.1.1

I recommend upgrading to 0.4. Serializing shared component is going through a different codepath where the shared components are actually serialized in the entity binary file.

1 Like