Skip to content

How to add/remove components at runtime

  1. Define your component types (classes):
1
2
class Position { constructor(public x = 0, public y = 0) {} }
class Velocity { constructor(public x = 0, public y = 0) {} }
  1. Add/remove immediately when you are not iterating a query:
1
2
3
4
5
6
7
8
9
const e = world.spawn();
world.add(e, Position, new Position(0, 0));
world.add(e, Velocity, new Velocity(1, 0));

// Or add many at once
const z = world.spawn();
world.addMany(z, [new Position(0, 0), new Velocity(1, 0)])

world.remove(e, Velocity);
  1. Add/remove during a query/system using deferred commands:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
world.addSystem((w: any) => {
  for (const { e, c1: pos } of w.query(Position)) {
    if (pos.x > 10) w.cmd().add(e, Velocity, new Velocity(1, 0));
    if (pos.x < 0)  w.cmd().remove(e, Velocity);
  }
});

// Or remove many at once
world.addSystem((w: any) => {
  for (const { e, c1: pos } of w.query(Position, Velocity)) {
    if (pos.x < 0)  w.cmd().removeMny(e, Position, Velocity);
  }
});

// apply queued structural changes
world.flush();