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: Un-register component keys down the component tree #2792

Merged
merged 3 commits into from
Oct 4, 2023
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
16 changes: 10 additions & 6 deletions packages/flame/lib/src/components/core/component.dart
Original file line number Diff line number Diff line change
Expand Up @@ -896,17 +896,12 @@ class Component {
void _remove() {
assert(_parent != null, 'Trying to remove a component with no parent');

if (_key != null) {
final game = findGame();
if (game is FlameGame) {
game.unregisterKey(_key!);
}
}
_parent!.children.remove(this);
propagateToChildren(
(Component component) {
component
..onRemove()
.._unregisterKey()
.._clearMountedBit()
.._clearRemovingBit()
.._setRemovedBit()
Expand All @@ -920,6 +915,15 @@ class Component {
);
}

void _unregisterKey() {
if (_key != null) {
final game = findGame();
if (game is FlameGame) {
game.unregisterKey(_key!);
}
}
}

//#endregion

//#region Debugging assistance
Expand Down
23 changes: 23 additions & 0 deletions packages/flame/test/components/component_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1381,6 +1381,29 @@ void main() {
},
);

testWithFlameGame(
'Removed keys can be reused by components',
(game) async {
final key = ComponentKey.named('A');
final parent1 = Component(children: [ComponentA(key: key)]);

game.world.add(parent1);
await game.ready();

parent1.removeFromParent();
await game.ready();

final component = ComponentA(key: key);
final parent2 = Component(children: [component]);

game.world.add(parent2);
await game.ready();

final retrieved1 = game.findByKey(key);
expect(retrieved1, equals(component));
},
);

testWithFlameGame(
'Throws assertion error when registering a component with the same key',
(game) async {
Expand Down