diff --git a/lib/src/entity.dart b/lib/src/entity.dart index 2a1e3cd..d2092ac 100644 --- a/lib/src/entity.dart +++ b/lib/src/entity.dart @@ -20,8 +20,7 @@ abstract class Entity extends PositionComponent { Iterable? children, int? priority, Iterable? behaviors, - }) : _behaviors = behaviors ?? [], - assert( + }) : assert( children?.whereType().isEmpty ?? true, 'Behaviors cannot be added to as a child directly.', ), @@ -34,10 +33,20 @@ abstract class Entity extends PositionComponent { children: children, priority: priority, ) { - addAll(_behaviors); + if (behaviors != null) { + addAll(behaviors); + } } - final Iterable _behaviors; + late final List _behaviors; + + @override + Future? onLoad() { + children.register(); + _behaviors = children.query(); + + return super.onLoad(); + } /// Returns a list of behaviors with the given type, that are attached to /// this entity. diff --git a/test/src/entity_test.dart b/test/src/entity_test.dart index a7ea26a..d066423 100644 --- a/test/src/entity_test.dart +++ b/test/src/entity_test.dart @@ -24,5 +24,23 @@ void main() { expect(entity.children.contains(behavior), isTrue); }); + + flameTester.test( + 'behavior can be removed from entity and the internal cache', + (game) async { + final behavior = TestBehavior(); + final entity = TestEntity(behaviors: []); + + await game.ensureAdd(entity); + + expect(entity.findBehavior(), isNull); + await entity.ensureAdd(behavior); + expect(entity.findBehavior(), isNotNull); + + behavior.shouldRemove = true; + game.update(0); + expect(entity.findBehavior(), isNull); + }, + ); }); }