From dd4a6097d948dc4638f51fc4969e6e629fc96cd2 Mon Sep 17 00:00:00 2001 From: GuoLei1990 Date: Thu, 6 Feb 2025 19:23:28 +0800 Subject: [PATCH] refactor: opt code --- packages/core/src/Scene.ts | 13 ++++++++----- tests/src/core/Entity.test.ts | 23 ++++++++++++++++++++--- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/packages/core/src/Scene.ts b/packages/core/src/Scene.ts index f76d0df417..84e8438e67 100644 --- a/packages/core/src/Scene.ts +++ b/packages/core/src/Scene.ts @@ -424,15 +424,18 @@ export class Scene extends EngineObject { const searchRootName = splits.shift(); for (let i = 0, n = this.rootEntitiesCount; i < n; i++) { - let rootEntity = this.getRootEntity(i); - if (rootEntity.name != searchRootName) { + let findEntity = this.getRootEntity(i); + if (findEntity.name !== searchRootName) { continue; } - const target = Entity._findChildByName(rootEntity, 0, splits, 0); - if (target) { - return target; + if (splits.length) { + findEntity = Entity._findChildByName(findEntity, 0, splits, 0); + if (!findEntity) { + continue; + } } + return findEntity; } return null; } diff --git a/tests/src/core/Entity.test.ts b/tests/src/core/Entity.test.ts index e2e96b66e8..e229d5780c 100644 --- a/tests/src/core/Entity.test.ts +++ b/tests/src/core/Entity.test.ts @@ -20,14 +20,22 @@ describe("Entity", async () => { const child = new Entity(engine, "child"); child.parent = parent; + + expect(scene.findEntityByPath("")).eq(null); + + expect(scene.findEntityByPath("root")).eq(scene.getRootEntity()); + expect(scene.findEntityByPath("root/parent")).eq(parent); expect(scene.findEntityByPath("root/parent/child")).eq(child); + + + }); it("not found", () => { const parent = new Entity(engine, "parent"); - parent.parent = scene.getRootEntity(); + const child = new Entity(engine, "child"); child.parent = parent; @@ -286,10 +294,19 @@ describe("Entity", async () => { parent.parent = scene.getRootEntity(); const child = new Entity(engine, "child"); child.parent = parent; - const child2 = new Entity(engine, "child2"); + const child2 = new Entity(engine, "child"); child2.parent = parent; + const child3 = new Entity(engine, "child"); + child3.parent = parent; + + const grandson = new Entity(engine, "grandsonX"); + grandson.parent = child; + const grandson2 = new Entity(engine, "grandson"); + grandson2.parent = child2; + + expect(parent.findByPath("/child")).eq(child); - expect(parent.findByPath("child2")).eq(child2); + expect(parent.findByPath("child/grandson")).eq(grandson2); }); it("clearChildren", () => {