Skip to content

Creating, getting and killing entities

Elliot Ford edited this page May 7, 2015 · 8 revisions

What is an EntityContainer?

An EntityContainer (API docs) is a store for entities. An Entity is also an EntityContainer (tree structure). JALSE offers a default implementation of EntityContainer, DefaultEntityContainer, which can also be used to create your own Entity implementation.

EntityContainer container = new DefaultEntityContainer();

When entities are created, transferred or killed they trigger listener events (see Creating an EntityListener).

Creating enitites

Creating an Entity will create the entity via the EntityFactory then assign it to this container. When an Entity is created it can be assigned a type and handed attributes and listeners before its creation event is triggered in the container. The newEntity method is overloaded:

  1. Specific UUID or random UUID.
  2. Type to be marked as or no type.
  3. Starting attributes or no attributes.

Below are some common examples:

Entity e = container.newEntity(); // Random ID
UUID id = /* Some unique ID */
Entity e = container.newEntity(id);
Animal a = container.newEntity(Animal.class);
AttributeContainer attributes = new DefaultAttributeContainer();
attributes.addAttribute("scared", Attributes.BOOLEAN_TYPE, true);

Animal a = container.newEntity(Animal.class, attributes);

Getting an Entity

Getting an Entity requires the ID. There are methods that 'cast' the entity as a supplied type and also Optional equivalents:

Entity e = container.getEntity(/* ID */);
Optional<Entity> optE = container.getOptEntity(/* ID */);
Animal e = container.getEntityAsType(/* ID */, Animal.class);
Optional<Animal> optE = container.getOptEntityAsType(/* ID */, Animal.class);

Killing an Entity

Killing an Entity can either be done at the container level with an ID or upon the entity itself (both remove from container):

Entity e = /* Some alive entity */
e.kill();

or

container.killEntity(/* ID */);

Using multiple entities

An EntityContainer can be used much like a Collection.

Total entity count: container.getEntityCount()

Stream entities: container.streamEntities()

Stream entities (marked as type): container.streamEntitiesOfType(Animal.class);

Stream entities ('cast' to type): container.streamEntitiesAsType(Animal.class);

All entities (Set): container.getEntities()

All entities (marked as type): container.getEntitiesOfType(Animal.class);

All entities ('cast' to type): container.getEntitiesAsType(Animal.class);

All entity IDs: container.getEntityIDs()

Kill all entities: container.killEntities()

Clone this wiki locally