diff --git a/packages/flame/lib/src/components/spawn_component.dart b/packages/flame/lib/src/components/spawn_component.dart index dbf5b63e0..5aaafcc08 100644 --- a/packages/flame/lib/src/components/spawn_component.dart +++ b/packages/flame/lib/src/components/spawn_component.dart @@ -26,6 +26,7 @@ class SpawnComponent extends Component { this.within = true, this.selfPositioning = false, this.autoStart = true, + this.spawnWhenLoaded = false, Random? random, super.key, }) : assert( @@ -48,6 +49,7 @@ class SpawnComponent extends Component { this.within = true, this.selfPositioning = false, this.autoStart = true, + this.spawnWhenLoaded = false, Random? random, super.key, }) : assert( @@ -107,6 +109,9 @@ class SpawnComponent extends Component { /// Whether the timer automatically starts or not. final bool autoStart; + /// Whether the timer should start when the [SpawnComponent] is loaded. + final bool spawnWhenLoaded; + @override FutureOr onLoad() async { if (area == null && !selfPositioning) { @@ -153,6 +158,7 @@ class SpawnComponent extends Component { amount++; }, autoStart: autoStart, + tickWhenLoaded: spawnWhenLoaded, ); timer = timerComponent.timer; add(timerComponent); diff --git a/packages/flame/test/components/spawn_component_test.dart b/packages/flame/test/components/spawn_component_test.dart index 19c82f169..1874a7740 100644 --- a/packages/flame/test/components/spawn_component_test.dart +++ b/packages/flame/test/components/spawn_component_test.dart @@ -166,5 +166,58 @@ void main() { await game.ready(); expect(world.children.length, 2); }); + + testWithFlameGame( + 'Does not spawns right away when spawnWhenLoaded is false (default)', + (game) async { + final random = Random(0); + final shape = Rectangle.fromCenter( + center: Vector2(100, 200), + size: Vector2.all(200), + ); + final spawn = SpawnComponent( + factory: (_) => PositionComponent(), + period: 1, + area: shape, + random: random, + ); + final world = game.world; + await world.ensureAdd(spawn); + expect(world.children.whereType(), isEmpty); + game.update(1.5); + await game.ready(); + expect( + world.children.whereType(), + hasLength(1), + ); + }, + ); + + testWithFlameGame( + 'Spawns right away when spawnWhenLoaded is true', + (game) async { + final random = Random(0); + final shape = Rectangle.fromCenter( + center: Vector2(100, 200), + size: Vector2.all(200), + ); + final spawn = SpawnComponent( + factory: (_) => PositionComponent(), + period: 1, + area: shape, + random: random, + spawnWhenLoaded: true, + ); + final world = game.world; + await world.ensureAdd(spawn); + expect(world.children.whereType(), hasLength(1)); + game.update(1.5); + await game.ready(); + expect( + world.children.whereType(), + hasLength(2), + ); + }, + ); }); }