Skip to content

Commit

Permalink
fix: getSceneName use scenes #3022 (#3023)
Browse files Browse the repository at this point in the history
Closes #3022

## Changes:

- Fixed `getSceneName` to use `scene`.

I didn't know how to use `_sceneToInstance` cache, so I replaced it with something simpler.
  • Loading branch information
aruru-weed authored and eonarheim committed May 5, 2024
1 parent 0385deb commit 6adef00
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 5 deletions.
32 changes: 27 additions & 5 deletions src/engine/Director/Director.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,13 +277,35 @@ export class Director<TKnownScenes extends string = any> {
return undefined;
}

getSceneName(scene: Scene) {
for (const [name, sceneInstance] of this._sceneToInstance) {
if (scene === sceneInstance) {
return name;
/**
* Returns the name of the registered scene, null if none can be found
* @param scene
*/
getSceneName(scene: Scene): string | null {
for (const [name, maybeScene] of Object.entries(this.scenes)) {
if (maybeScene instanceof Scene) {
if (scene === maybeScene) {
return name;
}
} else if (!isSceneConstructor(maybeScene)) {
if (scene === maybeScene.scene) {
return name;
}
}
}
return 'unknown scene name';

for (const [name, maybeScene] of Object.entries(this.scenes)) {
if (isSceneConstructor(maybeScene)) {
if (scene.constructor === maybeScene) {
return name;
}
} else if (!(maybeScene instanceof Scene)) {
if (scene.constructor === maybeScene.scene) {
return name;
}
}
}
return null;
}

/**
Expand Down
30 changes: 30 additions & 0 deletions src/spec/DirectorSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,36 @@ describe('A Director', () => {
engine.dispose();
});

it('can get a scene name', () => {
const engine = TestUtils.engine();
const clock = engine.clock as ex.TestClock;
clock.start();
const scene1 = new ex.Scene();
scene1._initialize(engine);
const scene2 = new ex.Scene();
scene2._initialize(engine);
const scene3 = new ex.Scene();
scene3._initialize(engine);

class SceneCtor1 extends ex.Scene {}
class SceneCtor2 extends ex.Scene {}

const sut = new ex.Director(engine, {
scene1,
scene2,
myScene: { scene: scene3 },
sceneWithCtor: { scene: SceneCtor1 },
ctor: SceneCtor2
});

expect(sut.getSceneName(scene1)).toBe('scene1');
expect(sut.getSceneName(scene2)).toBe('scene2');
expect(sut.getSceneName(scene3)).toBe('myScene');
expect(sut.getSceneName(new SceneCtor1())).toBe('sceneWithCtor');
expect(sut.getSceneName(new SceneCtor2())).toBe('ctor');
expect(sut.getSceneName(new ex.Scene())).toBe(null);
});

it('will draw a start scene transition', async () => {
const engine = TestUtils.engine();
const clock = engine.clock as ex.TestClock;
Expand Down

0 comments on commit 6adef00

Please sign in to comment.