Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: entity behavior cache is never cleared #10

Merged
merged 2 commits into from
May 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions lib/src/entity.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ abstract class Entity extends PositionComponent {
Iterable<Component>? children,
int? priority,
Iterable<Behavior>? behaviors,
}) : _behaviors = behaviors ?? <Behavior>[],
assert(
}) : assert(
children?.whereType<Behavior>().isEmpty ?? true,
'Behaviors cannot be added to as a child directly.',
),
Expand All @@ -34,10 +33,20 @@ abstract class Entity extends PositionComponent {
children: children,
priority: priority,
) {
addAll(_behaviors);
if (behaviors != null) {
addAll(behaviors);
}
}

final Iterable<Behavior> _behaviors;
late final List<Behavior> _behaviors;

@override
Future<void>? onLoad() {
children.register<Behavior>();
_behaviors = children.query<Behavior>();

return super.onLoad();
}

/// Returns a list of behaviors with the given type, that are attached to
/// this entity.
Expand Down
18 changes: 18 additions & 0 deletions test/src/entity_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<TestBehavior>(), isNull);
await entity.ensureAdd(behavior);
expect(entity.findBehavior<TestBehavior>(), isNotNull);

behavior.shouldRemove = true;
game.update(0);
expect(entity.findBehavior<TestBehavior>(), isNull);
},
);
});
}