Phaser 3 Graphics object

I am making a small game for kids.
I have the following lines in my code:
rectDrawn[i]=graphics.strokeRect(x, y, w, h);
rectDrawn[i].setDepth(2);

I am drawing a few rectangles and then when the problem is over I destroy the rectangles:

for(i=0;i<7;i++){
rectDrawn[i].destroy();
}
Then the kids start a new problem and I draw new rectangles. But that does not work. I get the following error:
Cannot read property ‘sys’ of undefined on the line rectDrawn[i].setDepth(2);
Can anyone tell me what is going on?

When you destroy() an object, you can’t use it anymore. In your case, you’re destroying the Graphics, then trying to draw to them again. Use clear() instead, which clears the contents o the Graphics object without destroying the object.

I also want to note that you don’t need separate Graphics objects to draw multiple shapes. You can call strokeRect many times on the same object, which conserves memory. If all you’re doing is drawing simple shapes, I’d also recommend looking into Rectangle shape objects instead of Graphics objects because they’re simpler and more performant.

2 Likes