flutterdartassetsflame

How to change the structure of asset locations in flame?


I'd like to change where the default structure of assets that flame uses. The documentation says

If you want to change this structure, this is possible by using the prefix parameter and creating your own instances of AssetsCache, ImagesCache, AudioCache and SoundPools, instead of using the global ones provided by Flame.

Documentation page for above

I know that we can use the prefix parameter, but I have no idea of how or where to access the shared instance so I can achieve this result.


Solution

  • Currently there are two places that the caches are instantiated in Flame, first we have the caches that are in your FlameGame that comes from the Game mixin, they can be changed by overriding them:

    class MyGame extends FlameGame {
      @override
      final images = Images(prefix: 'assets/special_images/');
      final assets = AssetsCache(prefix: 'assets/special_assets/');
      
      ...
    }
    

    Then we have the global caches in Flame.dart:

    class Flame {
      /// Flame asset bundle, defaults to the root bundle but can be globally
      /// changed.
      static AssetBundle bundle = rootBundle;
    
      /// Access a shared instance of [AssetsCache] class.
      static AssetsCache assets = AssetsCache();
    
      /// Access a shared instance of the [Images] class.
      static Images images = Images();
    
      /// Access a shared instance of the [Device] class.
      static Device device = Device();
    }
    

    These ones you can just re-assign to new caches with the prefixes that you want.