Jump to content

on receiving signal this.game is null


boris0dev
 Share

Recommended Posts

Hi,

I'm looking for an explanation for the following behaviour:

I have a class "Main" extending Phaser.State, a class "Emitter" and a class "Receiver" extending Phaser.Sprite

If I dispatch a signal from "Emitter" and listen to it in "Receiver" everything works as expected or to be more precise: "this.game" has the object "App" assigned.

If I reload the state and dispatch again the signal two things happen:

The listener receives the signal two times. 

The 1st time "this.game" is null, the 2nd time "this.game" contains again the object "App" (please have a look at the screenshot showing the console output)

Does anybody have an explanation for this behaviour? 

Thanks, Boris

The code (TypeScript)

export class Game extends Phaser.Game {
  constructor() {
    super(480, 640, Phaser.AUTO, 'content', null);
    this.state.add('Main', Main, true);

    console.log("Game started");
	 }
}

class Main extends Phaser.State {
	private emitter: Emitter;
	private receiver: Receiver;

	preload() {
      this.load.image('logo', 'assets/logo.png');
  }

	create() {
	  this.emitter = new Emitter(this.game);
	  this.receiver = new Receiver(this.game);

    const rKey = this.input.keyboard.addKey(Phaser.Keyboard.R);
    rKey.onDown.add(() => {
      console.log('reload state Main');
      this.game.state.start('Main',true,false);
    }, this);
  }
}

class Emitter {
  // -- Signals
  static onEventFromEmitter: Phaser.Signal = new Phaser.Signal();

	constructor(private game: Phaser.Game) {
    const spaceKey = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    spaceKey.onDown.add(() => {
        Emitter.onEventFromEmitter.dispatch();
    }, this);
  }
}

class Receiver extends Phaser.Sprite {
   constructor(game: Phaser.Game) {
     super(game, 0, 0, 'logo');
     this.game.add.existing(this);
     this.subscribe();
   }

   /**
    * Subscribe to events
    */
   private subscribe(): void {
     Emitter.onEventFromEmitter.add(() => {
       console.log('Game object in Receiver, listening to onEventFromEmitter', this.game);
    }, this);
  }
}

 

console output.png

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...