Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Generic Entity Remapping

Discussion in 'Entity Component System' started by ogimusprime, Oct 20, 2022.

  1. ogimusprime

    ogimusprime

    Joined:
    Jul 20, 2021
    Posts:
    11
    Hello! I am currently stumped on the last step of my deserialization process and decided to come to the forum for help. I have successfully serialized the components I care about from my entities and deserialized their saved values onto new entities. For some pointers on how to go about that, see DOTS 0.5 and Serialization.

    My issue is I now have new entities with varying IComponentData and/or IBufferElementData on them which contain invalid Entity references. When I deserialize and instantiate the new Entities, I create a NativeParallelHashmap<int2, Entity> for remapping purposes. Having a way to reference the new entity based on the serialized entity's Index/Version is not my issue. My issue is trying to figure out a generic way to go through all of the different component and buffer types on my new entities, determine which components/ buffers contain an Entity reference that needs to be updated, and then update said Entity reference.

    Can someone out there with more experience in generic methods point me in the right direction towards having a solution that will work on multiple different IComponentData or IBufferElementData types without hard-coding things?

    Thank you so much for the help!
     
  2. scottjdaley

    scottjdaley

    Joined:
    Aug 1, 2013
    Posts:
    160
    I'm using a json library that deserializes the component data in a generic recursive fashion. I overloaded how it serializes and deserializes entity references. During serialization, I save prefab IDs. During deserialization, whenever it finds an Entity field, I retrieve it from a map, or instantiate the corresponding prefab if its the first time seeing it.

    I believe the json library is using a bunch of reflection internally to traverse the component fields in a generic way. Its definitely not the most performant way to serialize/deserialize the game state, but it works fine for my use case.

    If you are trying to do something faster without reflection, I would look into how the ECS package handles entity remapping for things like runtime instantiation of a prefab. Instantiate will remap any self entity references in its components or the components of its children, so it is doing something pretty similar. A quick look around and I see
    TypeManager.GetEntityOffsets()
    and
    Archetype.ScalarEntityPatches
    which I believe are used for this purpose.