add method
- Component component
Schedules component to be added as a child to this component.
This method is robust towards being called from any place in the user code: you can call it while iterating over the component tree, during mounting or async loading, when the Game object is already loaded or not.
The cost of this flexibility is that the component won't be added right away. Instead, it will be placed into a queue, and then added later, after it has finished loading, but no sooner than on the next game tick.
This method is synchronous: it returns immediately without waiting for the
component to load or mount. This makes it safe to call from anywhere,
including inside update or a loop that spawns many components, without
having to await it or wrap it in unawaited. If you need to wait for a
particular lifecycle stage, await the child's loaded, mounted, or
removed future instead:
world.add(coin);
await coin.mounted;
// The coin is now guaranteed to be mounted.
When you add a whole batch of children and only care that all of them made
it into the tree, await FlameGame.lifecycleEventsProcessed once instead
of collecting the individual futures.
Awaiting loaded is safe from inside the parent's own onLoad, because
the child starts loading as soon as it is added. Awaiting mounted or
removed there is not: a child can only be mounted after its parent has
been, and the parent is only mounted once its onLoad has completed, so
those futures would deadlock. The same applies to
FlameGame.lifecycleEventsProcessed, since the parent's own pending
mount is part of the queue it waits for.
When multiple children are scheduled to be added to the same parent, we start loading all of them as soon as possible. Nevertheless, the children will end up being added to the parent in exactly the same order as they were originally scheduled by the user, regardless of how fast or slow each of them loads.
A component can be added to a parent which may not be mounted to the game tree yet. In such case, the component will start loading immediately, but its mounting will be delayed until such time when the parent becomes mounted.
A component can only be added to one parent at a time. It is an error to
try to add it to multiple parents, or even to the same parent multiple
times. If you need to change the parent of a component, use the
parent setter.
If component's onLoad throws, the component is never mounted and the
rest of the tree carries on unaffected. The error is reported through the
component's loaded future, and to the current Zone if nothing is
awaiting it.
Implementation
void add(Component component) => _addChild(component);