How to Access Component Data from an Entity?

Hello,

I’m having trouble understanding how to access data from components in other entities, as well as how to access another component’s data within the same entity.
The documentation isn’t very clear.

For example, I have two components:

Component One:

import * as ecs from '@8thwall/ecs'  // This is how you access the ecs library.

ecs.registerComponent({
  name: 'component-one',
  schema: {
    // Add data that can be configured on the component.
    age: ecs.i32,
  },
  schemaDefaults: {
    // Add defaults for the schema fields.
    age: 15,
  },
  data: {
    // Add data that cannot be configured outside of the component.
    pet: ecs.string,
  },
  add: (world, component) => {
    // Runs when the component is added to the world.
    component.data.pet = 'dog'
  },
})

Component Two:

import * as ecs from '@8thwall/ecs'  // This is how you access the ecs library.

ecs.registerComponent({
  name: 'component-two',
  schema: {
    // Add data that can be configured on the component.

  },
  schemaDefaults: {
    // Add defaults for the schema fields.
  },
  data: {
    // Add data that cannot be configured outside of the component.

  },
  add: (world, component) => {
    // Runs when the component is added to the world.
  },

These components might be in the same entity or in different ones.

  • How can I access the age and pet values from Component Two?
  • What does ecs.getAttribute() do?

Thank you!

Data isn’t accessible outside the current entity. To work around this, you’ll need to either use an event listener pattern or create an object that represents your component outside of the registration, which you can then import and use an instance of.

1 Like