Skip to content

Example: Working with components and entities

jsutlive edited this page May 13, 2023 · 2 revisions

Adding components to an Entity

To add a component to the entity, simply add a component object to the entity by calling the addComponent(Component c) method.

Entity e = new Entity();
ElasticForce force = new ElasticForce();
e.addComponent(force);

This can be simplified by using the .with(Component c) method, which can be chained to add any number of components to an entity when it is created. The components are added in order, so make sure components that are dependent on others are called later.

Entity e = new Entity().with(new ElasticForce());

Adding components within another component

It is not uncommon to require one component to reference another. It is typically best practice to add this reference in start() if the component only needs to be referenced when the simulation is running (play mode). If you need the reference in editor mode, the awake() method may be the better option. Remember to target the class type (with .class extension), not a specific instance of a class using the getComponent(Class componentClass) method.

@Override
Mesh mesh

void start(){
     mesh = getComponent(Mesh.class);
}

If the component hasn't been added to the parent yet, you can add it via code as well. You can do this in awake, or use a null check to prevent duplication of behaviors. Call this component's parent (or whatever entity you're referencing) and use its addComponent(Component c) method.

@Override
Mesh mesh

void start(){
     if(mesh == null){
          mesh = parent.addComponent(new RingCellMesh());
     }
}

Removing components

Remove a component by calling the removeComponent(Class componentClass) method, in the same way you would do when adding. Be careful cycling through for loops (see Concurrent Modification Exception).

void start(){     
     parent.removeComponent(ElasticForce.class)
}
Clone this wiki locally