0

Does removeFromParent destroys object? I mean Garbage collects it, I am looking for destroy method but couldn't find.

update:

import 'package:flame/components.dart';

class Enemy extends SpriteAnimationComponent with HasGameRef {
  @override
  Future<void>? onLoad() async {
    position = Vector2(200, 100);
    size = Vector2(100, 100);

    var spriteAnimationData = SpriteAnimationData.sequenced(
      amount: 12,
      stepTime: 0.05,
      textureSize: Vector2(30, 30),
    );

    animation =
        await gameRef.loadSpriteAnimation('enemy/pig.png', spriteAnimationData);
    anchor = Anchor.center;

    return super.onLoad();
  }

  @override
  void update(double dt) {
    position += Vector2(-2, 0);

    if (position.x < -20) {
      removeFromParent();
    }  

    super.update(dt);
  }
}
Davoud
  • 2,576
  • 1
  • 32
  • 53

1 Answers1

1

Since Dart is a garbage collected language it will garbage collect unused objects automatically once there are no references to the object anymore.

However, Sprites are a bit special since they have a loaded image in them. In Flame 1.0.0 the image cache (or the sprite class) does not call dispose of these images when it is cleared (but on main, and in the next version this will be done).

So to properly free up memory you'll have to call image.dispose() after you have removed the SpriteComponent, you could do sprite.image.dispose() in onRemove of the SpriteComponent for example, or call spriteComponent.sprite.image.dispose() after it has been removed.

EDIT: Since the question is now updated.

To call dispose on all Images loaded into a SpriteAnimationComponent you would have to do something like this:

component.animation.frames.forEach((f) => f.sprite.image.dispose());

Since those images are also loaded into the image cache they will also be removed when you remove an entry (or clear the whole cache) in the next version.

Reference: https://api.flutter.dev/flutter/dart-ui/Image/dispose.html

spydon
  • 9,372
  • 6
  • 33
  • 63
  • For being garbage collected automatically I've to remove any reference to the corresponding object, so I call `removeFromParent()` inside update method of enemy class if enemy is out of sight and it removes the objects, but does `removeFromParent()` removes all references to the object? How to see a list of added objects to the game to be sure removed object is deleted? I couldn't find the dispose method of `SpriteAnimationComponent`. – Davoud Jan 27 '22 at 09:34
  • Flame removes all internal references to it after it has been removed, so If you don't keep any references to the object yourself lying around it will get garbage collected. For `SpriteAnimationComponent` it is quite cumbersome to call `dispose` for all images in there (but this is also solved in the next version), you would have to call `component.animation.frames.forEach((f) => f.sprite.image.dispose());` – spydon Jan 27 '22 at 10:13