Skip to content

Creating Components

jdrueckert edited this page Mar 10, 2024 · 5 revisions

Components are defined by Java classes. In order to be a component, a class must have a name ending in Component (the rest of the name is used as the name of the component) and implement the interface org.terasology.entitySystem.Component.

Components are subject to some restrictions:

  1. Although components can technically hold methods, it is not recommended because it violates the boundaries of ECS. Components are for storing data, not executing code.
  2. Components are allowed to create their own constructors; however, they must keep a default constructor (one with no parameters) for internal use by the entity system.
  3. All variables in a component class must be public, and none can be static. In particular, private component fields will not be serialized, so any values will be lost between game sessions.
  4. Components are only allowed to contain variables of certain types (where T may be any type on the list):
    • All primitive types
    • String
    • Enum
    • Map<String, T>
    • List<T>
    • Set<T>
    • EntityRef
    • BlockFamily
    • Color4f
    • Vector2i, Vector2f, Vector3i, Vector3f
    • Quat4f
    • Texture
    • Prefab
    • MappedContainer (explained below)

Components may set default values for each of their variables as well. When default values are set, they do not need to be provided when defining an entity with the component.

public class DisplayComponent implements Component {
    public int num = 0;
}

This example defines a DisplayComponent with a single field called num which defaults to 0.

Mapped Containers

A mapped container is any class marked with the @MappedContainer annotation. Mapped containers are subject to the same restrictions as components, except that they do not need to have a name ending in Component and do not need to implement the Component interface. Mapped containers allow for larger components to manage complex data more easily by using objects.

Clone this wiki locally