This.add.sprite has error inside functions

I have this error every time I try to convert my code into a function

Uncaught TypeError: Cannot read properties of undefined (reading ‘sprite’)

var diceImages = [‘di1’, ‘di2’, ‘di3’, ‘di4’, ‘di5’, ‘di6’];
function preload() {
//load the dice images
for (var i = 0; i < diceImages.length; i++) {
this.load.image(diceImages[i], ‘assets/’ + diceImages[i] + ‘.png’);
}

function rollDice(){
dice1 = Math.floor(Math.random() * 6) + 1;
dice2 = Math.floor(Math.random() * 6) + 1;
dice3 = dice1 + dice2;

    // Get the names of the images to display based on the dice rolls
    const image1 = diceImages[dice1 - 1];
    const image2 = diceImages[dice2 - 1];
    // Display the images on the screen
    const firstDi = this.add.sprite(240, 230, image1);   //<== error is here at .sprite
    const secondDi = this.add.sprite(320, 230, image2);
    // Define the animation duration and number of rotations
    const duration = 1000; // in milliseconds
    const numRotations = 8;
    // Define the animation properties for both images
    const animationProps = {
        angle: 360 * numRotations,
        duration: duration,
        ease: 'Linear',
        onComplete: function() {
            // Re-enable the button after animation completes
            // diceButton1.setInteractive();
        }
    };
    // Apply the animation to both images simultaneously
    this.tweens.add({
        targets: [firstDi, secondDi],
        ...animationProps
    });

function create () {
diceButton1.on(‘pointerup’, function () {
rollDice(); //<== this is where I calleed the function
}, this)
}

When I place the code directly where the function is called it works fine. I only get the error when I put it into a function

the problem ist that the this object is not the the “correct one”.

the fast solution would be to use the call function (link to a javascript documentation)

you just need to change rollDice(); to rollDice.call(this); and than it should work.

Hope this helps

Thanks. Resolved using rollDice.call(this);

I just got the same eror again trying to call the function within a switch statement inside the diceButton1

function create () {
diceButton1.on(‘pointerup’, function () {
rollDice.call(this); //

switch (ASSETS[player1.position][0]) {
case “Bett-on Bets”:
//Randomly select betting option from betting array
betAudio.play();

                yesButton.on('pointerdown', function() {
                    betAudio.stop();
                    
                    rollDice.call(this);//<== I have the same error trying to call the function from here now

}, this)
}

When you pass a callback function that uses this, you must choose a value for it (the calling context).

You can pass this as the third argument to on(). Or you can change the callback to an arrow function.

Thanks, it worked with the arrow function