Skip to content

Conversation

@soulofmischief
Copy link

@soulofmischief soulofmischief commented Jan 23, 2025

This PR adds a symbol that can be used to key a default initializer function in a component. It throws if the initializer isn't a function.

The API is such:

import { $default, Default, addComponent, addEntity, createWorld } from 'bitECS'

const world = createWorld()
const eid = addEntity( world )

const MyComponent = {
  x: [] as number[],
  y: [] as number[],
  [$default]( eid, { x = 1, y = 1 } = {}) {
    MyComponent.x[ eid ] = x
    MyComponent.y[ eid ] = y
  }
}

addComponent( world, eid, MyComponent )
assert( MyComponent.x[ eid ] === 1 )

// or:
addComponent( world, eid, Default( MyComponent, { x: 42 }))

Not sure if you wanted direct support for a default initializer, but this seems like a non-intrusive way to do it. Anything I should change/add if you want to merge?

I know you mentioned in #105 that you wanted to avoid invoking GC or creating unnecessary objects, but this approach is entirely opt-in, doesn't modify the API, and only introduces one conditional check for the $default property.

It's up to the user to avoid invoking GC with the default method, but it's no different than the user just setting these values manually every time after adding a component, or using a prefab. We could also include a stronger warning in the docs. The Default() wrapper also gives the user a way to avoid double initialization.

@soulofmischief soulofmischief changed the title Add default initializer via $default method [v.0.4] Add default initializer via $default method Jan 23, 2025
@soulofmischief soulofmischief force-pushed the rc-0-4-0 branch 2 times, most recently from 0281b66 to 865e975 Compare January 23, 2025 12:28
@soulofmischief
Copy link
Author

Should $default and $defaultParams be non-enumerable?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant