NateTheGreatt / bitECS

Functional, minimal, data-oriented, ultra-high performance ECS library written in JavaScript
Mozilla Public License 2.0
902 stars 83 forks source link

getEntityComponents does not return component name #111

Open Tresky opened 1 year ago

Tresky commented 1 year ago

When I call getEntityComponents for an entity it returns the instances of the components, but does not tell me what the names of those components are. Is there a preferred method for determining the name of the components that are on an entity?

I realize that there probably is no way bitecs would know the name because we don't initialize the components with a name, but perhaps there is some specific way people organize their code to be able to keep a name?

I looked into adding a name into the bitecs codebase and making a PR, but my understanding of the code is fairly prohibitive of me making changes at this point.

NateTheGreatt commented 1 year ago

The most convenient way would probably be to simply compare references:

const SomeComponent = defineComponent()

const entityComponents = getEntityComponents(world, eid)

for (const component of entityComponents) {
  if (component === SomeComponent) {
    // ...
  }
}

Another way could be to keep a mapping around:

const componentNameMap = new Map()
const SomeComponent = defineComponent()
componentNameMap.set("SomeComponent", SomeComponent)

You can also tack names onto the component objects themselves using symbols to avoid namespace pollution/collision:

const $componentName = Symbol("componentName")
const SomeComponent = defineComponent()
SomeComponent[$componentName] = "SomeComponent"

Or even use a symbol per component:

const $someComponent = Symbol("someComponent")
const SomeComponent = defineComponent()
SomeComponent[$someComponent] = true