Event emitter , Can't communicate after scene restart/start again

Hi there

I have 4 scenes in my game. Boot, Menu, Game and GUI

“Game” and “GUI” scenes are connected together, and can communicate each other by using Event emitter

let ourGame = this.scene.get('main_game'); //GUI

let uiEvent = this.scene.get('game_ui'); //Game

This is a method what i used to show ‘GUI’ scene

this.scene.launch('game_ui'); //Game

This script are placed at top inside create() function on Game scene.

On first play, there is no problem at all.

But if Game scene are restarted or re-launch again, the problem are appears.

It’s like: Menu -> Game (GUI Launched) -> Back to Menu -> Start Game scene again -> Some ERROR

and the result are same if directly restart/relaunch Game scene

Here is a sample a text object before and after restart.

Before / First play
xc1

After / Second play
xc2

Object scene are undefined, even all object on GUI scene are already created and shown correctly, but i can’t change it’s text value, then return error.

I can send emit to ‘GUI’, but from ‘GUI’ can’t send to ‘Game’ via Event emitter, Sometimes a parameter from ‘Game’ to ‘GUI’ just return NaN

This is how i change the scene/back to menu

this.scene.stop('game_ui');
this.scene.start('game_menu');

Any help ?

What’s the error message and trace?

dsfdsx

Here is the error log if i’m trying to get the object.

Try to expand that trace.

It’s likely that object belongs to a removed scene.

Yes, i know, but i don’t know how to solve this or the best method to avoid this issue. i think event emitter keep using it’s first attached scene and not update it even after restarted.

Please check this http://cdn.redfoc.com/test/scene_test2/ and open console.log

My previous topics/problem are related to this.

class GUI extends Phaser.Scene {
	constructor(){
		super('game_ui');
	}
	create(){
		let txt = this.add.text(20, 20, 'press "E" to change text\npress "R" to restart',{fontFamily: 'Arial', fontSize: '25px',color: '#fff'});
		let txt_change = this.add.text(20, 200, 'TEXT',{fontFamily: 'Arial', fontSize: '25px',color: '#fff'});

		let ourGame = this.scene.get('game');

        ourGame.events.on('text', function (data) {
            txt_change.setText(String(data));
            console.log(txt_change);
        }, this);
	}
}
class GAME extends Phaser.Scene {
	constructor(){
		super('game');
	}
	create(){
		this.scene.launch('game_ui');

		this.input.keyboard.on('keydown', function (eventName, event){
	        var key = eventName.key;
	        if(key == 'r'){
	        	console.log('restart');
	          this.scene.start('game'); //restart
	        }
	        else if(key == 'e'){
	          this.events.emit('text', Math.random()*100);
	        }
	    }, this);
	}
}

It’s because the original event handler is never removed.

Add before ourGame.events.on('text', …):

ourGame.events.off('text');
2 Likes

Thank you it’s working