From c68e16456e48ce13289dbccfef6c573badac5c79 Mon Sep 17 00:00:00 2001
From: cosmonaut <evan@moonside.games>
Date: Fri, 19 May 2023 13:24:26 -0700
Subject: [PATCH] run Filter callbacks before updating component storage

---
 src/System.cs | 3 ++-
 src/World.cs  | 3 ++-
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/src/System.cs b/src/System.cs
index ea59464..eb87a46 100644
--- a/src/System.cs
+++ b/src/System.cs
@@ -19,8 +19,9 @@ namespace MoonTools.ECS
 		{
 			if (EntityStorage.RemoveComponent(entity.ID, ComponentTypeIndices.GetIndex<TComponent>()))
 			{
-				ComponentDepot.Remove<TComponent>(entity.ID);
+				// Run filter storage update first so that the entity state is still valid in the remove callback.
 				FilterStorage.Check<TComponent>(entity.ID);
+				ComponentDepot.Remove<TComponent>(entity.ID);
 			}
 		}
 
diff --git a/src/World.cs b/src/World.cs
index 8f7b2cc..6a04493 100644
--- a/src/World.cs
+++ b/src/World.cs
@@ -90,8 +90,9 @@ namespace MoonTools.ECS
 		{
 			foreach (var componentTypeIndex in EntityStorage.ComponentTypeIndices(entity.ID))
 			{
-				ComponentDepot.Remove(entity.ID, componentTypeIndex);
+				// Run filter storage update first so that the entity state is still valid in the remove callback.
 				FilterStorage.RemoveEntity(entity.ID, componentTypeIndex);
+				ComponentDepot.Remove(entity.ID, componentTypeIndex);
 			}
 
 			foreach (var relationTypeIndex in EntityStorage.RelationTypeIndices(entity.ID))