Texts[textIndex] = this.add.text( ); // ERROR Cannot read properties of undefined (reading 'text')?

Hi,

Trying to make a draw text function but it’s not working.

Get error on below line:

Texts[textIndex] = this.add.text( );
// ERROR: "Cannot read properties of undefined (reading 'text')"?

Please view below source code and suggest a fix, thanks!

Jesse

var ScreenCenterX;
var ScreenSizeX;

const TextsMax = 999;
var Texts = [TextsMax];
var CurrentTextIndex = 0;
const JustifyLeft = 0;
const JustifyCenter = 1;
const JustifyRight = 2;
const JustifyCenterOnPoint = 3;

function DrawText (textIndex, text, x, y, horizontalJustification, scaleX, scaleY, rotation, red, green, blue, alpha, outlineRed, outlineGreen, outlineBlue)
{
    //    ScreenCenterX = this.config.cameras.main.worldView.x + (this.config.cameras.main.width / 2); // Error when executed?

    if (textIndex == CurrentTextIndex)
    {

        Texts[textIndex] = this.add.text( ); // ERROR: "Cannot read properties of undefined (reading 'text')"?
        Texts[textIndex].setOrigin(0.5);
    }

    Texts[textIndex].text = text;

    if (horizontalJustification === JustifyLeft)
    {
        Texts[textIndex].x = x;
    }
    else if (horizontalJustification === JustifyCenter)
    {
        Texts[textIndex].x = ScreenCenterX;
    }
    else if (horizontalJustification === JustifyRight)
    {
        Texts[textIndex].x = (ScreenSizeX - x);
    }
    else if (horizontalJustification === JustifyCenterOnPoint)
    {
        Texts[textIndex].x = ( x - (Texts[textIndex].width / 2) );
    }

    Texts[textIndex].y = y;

    Texts[textIndex].scaleX = scaleX;
    Texts[textIndex].scaleY = scaleY;

    Texts[textIndex].rotation = rotation;

    var fillColor = new Phaser.Display.Color(red, green, blue);
    Texts[textIndex].color = fillColor.color;

    Texts[textIndex].setAlpha(alpha / 255);

    var outlineColor = new Phaser.Display.Color(outlineRed, outlineGreen, outlineGlue);
    Texts[textIndex].setStroke(outlineColor.color, 3);

    if (textIndex == CurrentTextIndex)
    {
        CurrentTextIndex++;
        if (CurrentTextIndex > TextsMax)
        {
            CurrentTextIndex = 0;
        }
    }

}

I think you’ve lost the scene context (this), so this.add is undefined.

Call as DrawText.call(this, …).