0

I want to reset game to its initial state and removing all the components in a method. After resetting I get this error:

Bad state: Cannot find reference TurtleGame in the component tree

It seems the gameRef doesn't loaded already even if I have HasGameRef mixin in the signature of the class. Why gameRef has reference to the game when first time the game starts and the player component works correctly! but after resetting gameRef reference is missing?

Davoud
  • 2,576
  • 1
  • 32
  • 53
  • Can you add some more information about how you are resetting your game and how you are removing your components? – spydon Feb 16 '22 at 19:24

2 Answers2

0

You can only access gameRef as long as the Component is mounted in the component tree. So you can't access it in the constructor for example, or after the component has been removed (until it is fully added to the tree again).

Override onLoad if you need to access it the first time the component is loaded and override onMount if you need to access it every time that the component is added to the component tree.

class YourComponent extends Component with HasGameRef<MyGame> {
  @override
  Future<void> onLoad() {
    // Only runs once, when the component is loaded.
    print(gameRef.size.y);
  }

  @override
  void onMount() {
    // Runs every time that the component is added to the component tree.
    print(gameRef.size.y);
  }
}
spydon
  • 9,372
  • 6
  • 33
  • 63
0

For a component with HasGameRef to acess the game reference either

  1. The component needs to be added to the game inside the game class like this:

    MyGame extends FlameGame{
       @override 
       FutureOr<void> onLoad(){
         add(MyComponent());
       }
    }
    

and if the component is removed it will loose access to the reference, so there's an alternative

  1. Use the find game method so your component can use this method to find the game reference even after it has been removed like this:

    class MyComponent extends SpriteComponent with HasGameRef {
        MyComponent(this.myGame);
        Game? myGame;
    
        @override
        Game? findGame() {
           return myGame ?? super.findGame();
        }
    }
    
Andrea herrera
  • 81
  • 1
  • 11