From 0b808f6ab1cd439ebf85ae1a1ddf3e9277b1908a Mon Sep 17 00:00:00 2001 From: dgflash Date: Sun, 8 Mar 2026 13:59:24 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96CCEntity=E7=9A=84addPrefab?= =?UTF-8?q?=E3=80=81addUi=E5=BC=82=E6=AD=A5=E6=93=8D=E4=BD=9C=E6=97=B6?= =?UTF-8?q?=EF=BC=8C=E5=AF=B9=E8=B1=A1=E8=A2=AB=E9=87=8A=E6=94=BE=E6=97=B6?= =?UTF-8?q?=E7=A9=BA=E5=AF=B9=E8=B1=A1=E9=97=AE=E9=A2=98=EF=BC=8C=E6=8F=90?= =?UTF-8?q?=E9=AB=98=E6=A1=86=E6=9E=B6=E7=A8=B3=E5=AE=9A=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- assets/module/common/CCEntity.ts | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/assets/module/common/CCEntity.ts b/assets/module/common/CCEntity.ts index 5f25d3a..52e3030 100644 --- a/assets/module/common/CCEntity.ts +++ b/assets/module/common/CCEntity.ts @@ -81,13 +81,14 @@ export abstract class CCEntity extends ecs.Entity { * @param parent 显示对象父级 * @param path 显示资源地址(可选,不传时使用 @game.prefab 装饰器注册的路径) * @param bundleName 资源包名称(可选,不传时使用 @game.prefab 装饰器注册的包名) + * @returns 预制体节点,如果实体已销毁则返回 null */ async addPrefab( ctor: ViewCtor, parent: View, path?: string, bundleName?: string - ): Promise { + ): Promise { // 未传入路径时,从装饰器注册的数据中获取 if (path == null) { path = (ctor as any).GAME_PREFAB_PATH; @@ -102,6 +103,14 @@ export abstract class CCEntity extends ecs.Entity { // 跟随父节点释放自动释放当前资源 if (parent instanceof GameComponent) { node = await parent.createPrefabNode(path, bundleName); + + // 检查实体是否已销毁 + if (!this.isValid) { + console.warn(`实体已销毁,取消添加预制体组件: ${(ctor as any).name}`); + node.destroy(); + return null; + } + const comp = node.getComponent(ctor); if (comp) this.add(comp as unknown as ecs.Comp); node.parent = parent.node; @@ -109,6 +118,14 @@ export abstract class CCEntity extends ecs.Entity { // 手动内存管理 else { node = await ViewUtil.createPrefabNodeAsync(path, bundleName); + + // 检查实体是否已销毁 + if (!this.isValid) { + console.warn(`实体已销毁,取消添加预制体组件: ${(ctor as any).name}`); + node.destroy(); + return null; + } + const comp = node.getComponent(ctor); if (comp) this.add(comp as unknown as ecs.Comp); node.parent = parent; @@ -134,9 +151,9 @@ export abstract class CCEntity extends ecs.Entity { * 添加视图层组件 * @param ctor 界面逻辑组件(支持 CCView 或使用 gui.register 注册的 GameComponent 子类) * @param params 界面参数 - * @returns 界面节点 + * @returns 界面节点,如果实体已销毁则返回 null */ - async addUi(ctor: UICtor, params?: UIParam): Promise { + async addUi(ctor: UICtor, params?: UIParam): Promise { const key = gui.internal.getKey(ctor); if (!key) { throw new Error(`${ctor.name} 界面组件未使用 gui.register 注册`); @@ -155,6 +172,14 @@ export abstract class CCEntity extends ecs.Entity { } const node = await oops.gui.open(key, params); + + // 检查实体是否已销毁 + if (!this.isValid) { + console.warn(`实体已销毁,取消添加界面组件: ${key}`); + oops.gui.remove(key); + return null; + } + const comp = node.getComponent(ctor) as unknown as ecs.Comp; if (comp) this.add(comp);