Problem in destroying a object

Is a better way to destroy a shape while in onUpdate when the “has clicked” becomes true but I have encountered some error

    spawnNote() {
        let missStatus = false;
        const finalRadius = 1050;
        const r3 = this.add.circle(1200 / 2, 700 / 2, 10);

        this.physics.add.existing(r3);
        r3.setStrokeStyle(10, 0xffffff);
        r3.body.setCollideWorldBounds(false);

        let destroyAfterUpdate = false; // Flag to mark for destruction

        this.tweens.add({
            targets: r3,
            radius: finalRadius,
            duration: 2000,
            ease: 'Linear',
            onUpdate: () => {
                if (r3 && !r3.isDestroyed) { // Check if r3 is still valid and not marked for destruction
                    r3.body.setCircle(r3.radius);
                }

                // Check if the circle should be destroyed in the update
                if (destroyAfterUpdate || hasClicked) {
                    r3.destroy();
                }
            },
            onComplete: () => {
                // Mark the object for destruction after the tween is complete
                destroyAfterUpdate = true;
            }
        });


        this.notes.push(r3)

}

the error that I encounter:


> phaser.esm.js:74328 Uncaught TypeError: Cannot set properties of null (setting 'radius')
>     at Arc.set [as radius] (phaser.esm.js:74328:30)
>     at TweenData.update (phaser.esm.js:236244:29)
>     at Tween.update (phaser.esm.js:235154:29)
>     at TweenManager.step (phaser.esm.js:230416:23)
>     at TweenManager.update (phaser.esm.js:230375:18)
>     at EventEmitter.emit (phaser.esm.js:208:33)
>     at Systems.step (phaser.esm.js:195858:16)
>     at SceneManager.update (phaser.esm.js:193095:21)
>     at Game.step (phaser.esm.js:17174:20)
>     at TimeStep.step (phaser.esm.js:18198:14)

If you destroy the tween target you need to also stop the tween.

I think something like this could work:

this.tweens.add({
	targets: r3,
	radius: finalRadius,
	duration: 2000,
	ease: "Linear",
	onUpdate: (tween) => {
		r3.body.setCircle(r3.radius);

		if (hasClicked) {
			tween.stop();
		}
	},
	onComplete: () => {
		r3.destroy();
	},
	onStop: () => {
		r3.destroy();
	},
});

You could also just call tween.stop() when the click happens.

2 Likes