Uncaught TypeError: Cannot read properties of undefined (reading:pick)

Hi Guys, I am new to babylon, so not sure what I have done wrong. I have this class that I am trying get a hit on what is under the mouse pointer.

export default class Wall extends GameObject {
	CurrentGame: Game;
	CurrentScene: Scene;

	constructor(game: Game) {
		super("Wall", game);
		this.CurrentGame = game;
		this.CurrentScene = game.scene;
		this.RegisterObserver();
	}

	RegisterObserver() {
		this.scene.onPointerObservable.add(this.HandlePointerAction);
	}

	HandlePointerAction(pInfo: PointerInfo) {
		// console.log(pInfo);
		// console.log(evt);

		console.log(pInfo.event.x + ", " + pInfo.event.y);

		var Hit = this.CurrentScene.pick(
			pInfo.event.x,
			pInfo.event.y,
			(pickedMesh) => pickedMesh.name == "Ground"
		);
		
		switch (pInfo.type) {
			case PointerEventTypes.POINTERDOWN:
				//console.log(Hit);
				break;
			case PointerEventTypes.POINTERMOVE:
				break;
		}
	}
}

I keep getting this error message. Not sure why.

Hi @gladiator-media
Common scope issue with observables :slight_smile:

this.scene.onPointerObservable.add(this.HandlePointerAction);

var Hit = this.CurrentScene.pick

this is no longer your class object, but the callback function, so CurrentScene is undefined.

There are multiple methods to solve this, here’s two popular ones
wrap it in another function and use a variable reference for this

RegisterObserver() {
	const _this = this;

	this.scene.onPointerObservable.add( (evt) => {
		_this.HandlePointerAction(evt);
	});
}

or binding the function

RegisterObserver() {
	this.scene.onPointerObservable.add( this.HandlePointerAction.bind(this) );
}
1 Like

Thank you! That makes sense. I had a feeling it was a scope issue.