Rolling back entities to cached state

Hi,

I’m working on a game with isolated levels and I want to be able reset them quickly, either on death or by player input. I don’t want to reload the entire scene, instead I would like to cache the state of relevant entities at level load and just reset them to that state when needed.

The following is my current approach. After loading the level I copy the entities to an empty world and disable the monobehaviour render components that I added as hybrid components. So far everything seems to work as expected.

To restore them I destroy the original entities and copy them back from the cache world. This works fine for “pure” entities, but the hybrid components are no longer attached to the correct entities and get mixed up somehow. Maybe a problem with the link companion objects?

I’d appreciate any ideas or better solutions to this kind of problem altogether. :wink:

public class ResetLevelSystem : SystemBase
{
   private World _cacheWorld;
   private EntityQuery _entitiesToCache;
   private NativeArray<Entity> _original;
   private NativeArray<Entity> _cached;

   protected override void OnCreate()
   {
      _cacheWorld = new World("LevelCache");
      _entitiesToCache = GetEntityQuery(ComponentType.ReadOnly<ResetEntityTag>());
   }

   public void CacheLevel()
   {
      _original = _entitiesToCache.ToEntityArray(Allocator.Persistent);
      _cached = new NativeArray<Entity>(_original, Allocator.Persistent);

      _cacheWorld.EntityManager.CopyEntitiesFrom(EntityManager, _original, _cached);
      _cacheWorld.GetOrCreateSystem<DisableRenderComponentsSystem>().Update();
   }

   public void ResetLevelToCachedState()
   {
      EntityManager.DestroyEntity(_original);
      EntityManager.CopyEntitiesFrom(_cacheWorld.EntityManager, _cached, _original);
      EntityManager.World.GetOrCreateSystem<EnableRenderComponentsSystem>().Update();
   }
}
1 Like

Mmhhh, after integrating it properly with my systems it works correctly, seems it was an issue with the system update order. Still, if anyone has a more elegant solution, hit me up.