How to fix this error "Cannot read property 'setVelocityX' of undefined"?

When I pause the scene and when I get back it throws this error. this is the code:

this the main scene:

let mainscene = new Phaser.Scene('main')

mainscene.preload = function() {
	this.load.image('player', 'player.png');
}

mainscene.create = function(){
	
	player = this.physics.add.image(250, 525, 'player');
	player.body.setAllowGravity(false)
	player.body.collideWorldBounds = true;

		//if key is pressed (I deleted the code that don't have a relation with the problem) {
		this.scene.start("fs");
		this.scene.pause('main');
	}
cursors = this.input.keyboard.createCursorKeys();
}
	
mainscene.update = function() {
		if (cursors.left.isDown) {player.setVelocityX(-260);}
	else if (cursors.right.isDown) {player.setVelocityX(260);}
	else if (cursors.down.isDown) {player.setVelocityY(260);}
	else if (cursors.up.isDown) {player.setVelocityY(-260);}
	else {player.setVelocityX(0);player.setVelocityY(0);}
	}

this is the pause scene:

let pausescene = new Phaser.Scene('fs')

pausescene.create = function() {
	
		// if key is pressed{
			game.scene.resume('main');
			game.scene.stop('fs');
			}
}

scene.start() stops the scene it belongs to. If you try to resume from there it will fail because the game objects no longer exist (in this case, player).

I think what you probably want instead is

// mainscene
this.scene.switch('fs');

// pausescene
this.scene.switch('main');
1 Like

thanks a lot, that worked