I have this repeated method to call an event to update keys and hearts on top of the screen …
Every scenes have this updateInventory() method repeated in gameScene, room1, room2, room3 when either keys or hearts changes…
Q: How do I have a common method shared across scenes but stil able to use this.scene.get
I tried a global function updateInventory() { … } but the this.scene.get is not working anymore…
Code here :
Common method that calls showInventory scene…
updateInventory() {
// Emit events showInventory
this.inventory = {}
this.inventory.heart = window.heart
this.inventory.key = window.key
console.log('Emit event', this.inventory)
this.invEvent = (event, data) => this.scene.get('showInventory').events.emit(event, data);
this.invEvent("inventory", this.inventory);
}
samme
2
Using call()
:
function updateInventory() {
this.scene.get(); // etc.
}
class gameScene extends Phaser.Scene {
// …
create() {
updateInventory.call(this);
}
}
With addEvent()
you pass callbackScope
instead:
function updateInventory() {
this.scene.get(); // etc.
}
class gameScene extends Phaser.Scene {
// …
create() {
this.time.addEvent({
// …
callback: updateInventory,
callbackScope: this,
});
}
}
1 Like
Thanks a lot, really appreciate it…
I have been repeating the same function over and over again in all the scenes…
Are they any drawbackls of using global functions ???