Skip to content

Commit 350abcd

Browse files
authored
🔀 Merge pull request #111 from wrangelvid/fixed_reset_world
fix: ensure entities are only destroyed when present
2 parents 16adec7 + f8d5e1e commit 350abcd

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

packages/core/src/world/world.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,13 @@ export class World {
128128
const ctx = this[$internal];
129129

130130
// Destroy all entities so any cleanup is done.
131-
this.entities.forEach((entity) => destroyEntity(this, entity));
131+
this.entities.forEach((entity) => {
132+
// Some relations may have caused the entity to be destroyed before
133+
// we get to them in the loop.
134+
if (this.has(entity)) {
135+
destroyEntity(this, entity)
136+
}
137+
});
132138

133139
ctx.entityIndex = createEntityIndex(this.#id);
134140
ctx.entityTraits.clear();

packages/core/tests/world.test.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { beforeEach, describe, expect, it } from 'vitest';
2-
import { createWorld, TraitInstance } from '../src';
2+
import { createWorld, relation, TraitInstance } from '../src';
33
import { trait } from '../src/trait/trait';
44
import { universe } from '../src/universe/universe';
55

@@ -27,6 +27,24 @@ describe('World', () => {
2727
expect(world.entities.length).toBe(1);
2828
});
2929

30+
it('reset should remove entities with auto-remove relations', () => {
31+
const Node = trait();
32+
const ChildOf = relation({ autoRemoveTarget: true, exclusive: true });
33+
34+
const world = createWorld();
35+
36+
// Create a parent node and a child node.
37+
const parentNode = world.spawn(Node);
38+
world.spawn(Node, ChildOf(parentNode));
39+
40+
// Expect this to not throw, since the ChildOf relation will automatically
41+
// remove the child node when the parent node is destroyed first.
42+
expect(() => world.reset()).not.toThrow();
43+
44+
// Always has one entity that is the world itself.
45+
expect(world.entities.length).toBe(1);
46+
});
47+
3048
it('errors if more than 16 worlds are created', () => {
3149
for (let i = 0; i < 16; i++) {
3250
createWorld();

0 commit comments

Comments
 (0)