I have create updateCanvas() function in file a.ts:
export class loadscene extends Scene {
textures1!: any
textures2!: any
textures3!: any
constructor() {
const key = 'loadscene'
super(key)
}
updateCanvas(scene){
switch (scene) {
case 'canvastextures1':
this.textures1.update()
break
case 'canvastextures2':
this.textures2.update()
break
case 'canvastextures3':
this.textures3.update()
break
}
}
}
and in file b.ts I call to use this function but not working:
import { loadscene } from './load.scene'
export class BattleScene extends Scene {
loadScene!: loadscene
...
this.loadScene = new loadscene()
this.loadScene.updateCanvas(tile.body.gameObject.texture.key)
I can use the function in the internal file but cannot call from another file. Does anyone have any ideas? Thank you.
CodePudding user response:
Well, I assume the problem is this line this.loadScene = new loadscene()
.
When you initializing the property this.loadScene
, you would have to get the created scene, not create a new one.
like this: this.loadScene = this.scene.get('loadscene')
.
This should work (if the compilier, throws an error, you should change the property from loadScene!: loadscene
to loadScene!: any
, or may a cast could work like this.loadScene = (this.scene.get('loadscene') as loadscene )
).
P.s.: I would change the parameter of the method updateCanvas(scene)
, scene
could be misunderstund since the parameter is the key of the texture.
And start the class names with uppercase. so class LoadScene...
would be better.
Update:
code in codepen shows, how I would use typescript to call functions from another scene
Here the relevant code (without the texture part):.
class FirstScene extends Phaser.Scene {
constructor() {
super('firstScene')
}
create(){
console.log('Create Call in First Scene!')
this.scene.start('secondScene')
}
testME(){
console.info('TEST ME')
return `called function "testME" from scene:${this.scene.key}`;
}
}
class SecondScene extends Phaser.Scene {
parentScene: any
constructor() {
super('secondScene')
}
create(){
let text = this.add.text(10,10, '"Create" in Second Scene!', {'color':'#fff'});
this.parentScene = this.scene.get('firstScene')
let newLine = this.parentScene.testME();
text.setText(text.text '\n' newLine);
}
}