Skip to content
Edward edited this page Jul 31, 2020 · 9 revisions

Prefabs allow cheap cloning of entities from a json file. The parsed json is cached. Allows custom loading mechanics.

since 2.1.0+

Usage

Getting started

Set up Serialization in your world. Prefabs are available in artemis-odb-serializer-json-libgdx and artemis-odb-serializer-json.

Basic prefab

@PrefabData("prefab/bunny.json")
public class BunnyTemplate extends Prefab {
    public BunnyTemplate(World world) {
        super(world, new JsonValuePrefabReader());
        // For libGDX users, you will need to provide JsonValuePrefabReader with a FileHandleResolver, i.e.
        // super(world, new JsonValuePrefabReader(new ClasspathFileHandleResolver()));
    }
}

See libgdx-json#using-the-serializer for instructions on how to create bunny.json in the first place.

Using prefab

public class MySpawnerSystem extends BaseSystem {

    private BunnyTemplate bunnyTemplate;

    @Override
    protected void initialize() {
      bunnyTemplate = new BunnyTemplate(world);
    }

    @Override
    protected void processSystem() {
          // spawn all entities from bunny.json in world. Does not replace existing bunnies.
          SaveFileFormat l = bunnyTemplate.create(); 
          Entity bunny = l.get("bunny"); // get by SerializationTag.
    }
}

Dependency injection

Prefabs support dependency injection. Can be used to tweak spawned entities slightly.

@PrefabData("prefab/player.json")
public class PlayerPrefab extends Prefab {
    private ComponentMapper<Position> positionMapper;

    public PlayerPrefab(World world) {
        super(world, new FallbackFileResolver());
    }

    public SaveFileFormat create(float x, float y) {
        SaveFileFormat l = create();
        Entity player = l.get("player");
        positionMapper.get(player).xy.set(x, y);
        return l;
    }
}

Custom prefab loading

  • One Prefab creates 1 type of prefab specialization (uses same source json)
    • custom PrefabReader<JsonValue> implementations can be used for more dynamic/polymorphic prefabs
  • @PrefabData(path) is passed to the FileHandleResolver
    • If you need more control: implement PrefabReader<JsonValue> (say because you want to different behavior on desktop vs mobile, e.g. non-caching vs caching)

Related to

  • #439 Near zero overhead json prefabs.
Clone this wiki locally