File tree Expand file tree Collapse file tree 3 files changed +19
-1
lines changed
Expand file tree Collapse file tree 3 files changed +19
-1
lines changed Original file line number Diff line number Diff line change @@ -171,6 +171,8 @@ bun run examples/simple/demo.ts
171171
172172- ` new() ` : 创建新实体
173173- ` set(entity, componentId, data) ` : 向实体添加组件
174+ - ` get(entity, componentId) ` : 获取实体的组件数据(注意:只能获取已设置的组件,使用前请先用 ` has() ` 检查组件是否存在)
175+ - ` has(entity, componentId) ` : 检查实体是否拥有指定组件
174176- ` delete(entity, componentId) ` : 从实体移除组件
175177- ` setExclusive(componentId) ` : 将组件标记为独占关系
176178- ` createQuery(componentIds) ` : 创建查询
@@ -251,6 +253,7 @@ const restored = World.deserialize(readySnapshot);
251253
252254注意事项
253255
256+ - ** 重要警告** :` get() ` 方法只能获取实体已设置的组件。如果尝试获取不存在的组件,会抛出错误。由于 ` undefined ` 是组件的有效值,不能使用 ` get() ` 的返回值是否为 ` undefined ` 来判断组件是否存在。请在使用 ` get() ` 之前先用 ` has() ` 方法检查组件是否存在。
254257- 快照只包含实体、组件、以及 ` EntityIdManager ` 的分配器状态(用于保留下一次分配的 ID);并不会自动恢复已注册的系统、查询缓存或生命周期钩子。恢复后应由应用负责重新注册系统与钩子。
255258- 若需要跨版本兼容,建议在持久化格式中包含 ` version ` 字段,并在恢复时进行格式兼容性检查与迁移。
256259
Original file line number Diff line number Diff line change @@ -79,7 +79,9 @@ describe("World", () => {
7979 world . delete ( entity , positionComponent ) ;
8080 world . sync ( ) ;
8181 expect ( world . has ( entity , positionComponent ) ) . toBe ( false ) ;
82- expect ( ( ) => world . get ( entity , positionComponent ) ) . toThrow ( / ^ C o m p o n e n t t y p e \d + i s n o t i n t h i s a r c h e t y p e $ / ) ;
82+ expect ( ( ) => world . get ( entity , positionComponent ) ) . toThrow (
83+ / ^ E n t i t y \d + d o e s n o t h a v e c o m p o n e n t \d + \. U s e h a s \( \) t o c h e c k c o m p o n e n t e x i s t e n c e b e f o r e c a l l i n g g e t \( \) \. $ / ,
84+ ) ;
8385 } ) ;
8486
8587 it ( "should throw error when removing invalid component type" , ( ) => {
Original file line number Diff line number Diff line change @@ -265,6 +265,19 @@ export class World<UpdateParams extends any[] = []> {
265265 if ( ! archetype ) {
266266 throw new Error ( `Entity ${ entityId } does not exist` ) ;
267267 }
268+
269+ // Check if entity has the component before attempting to get it
270+ // Note: undefined is a valid component value, so we cannot use undefined to check existence
271+ const detailedType = getDetailedIdType ( componentType ) ;
272+ if ( detailedType . type !== "wildcard-relation" ) {
273+ // For regular components, check if the component type exists in the archetype
274+ if ( ! archetype . componentTypes . includes ( componentType ) ) {
275+ throw new Error (
276+ `Entity ${ entityId } does not have component ${ componentType } . Use has() to check component existence before calling get().` ,
277+ ) ;
278+ }
279+ }
280+
268281 return archetype . get ( entityId , componentType ) ;
269282 }
270283
You can’t perform that action at this time.
0 commit comments