How to remove a background created using setBackgroundDrawingCallback?

My game has a title screen, and a gameplay screen.

I'm having trouble with changing the backgrounds between screens.

My gameplay screen is created by instancing a "Level" class, which in it's init function, calls setBackgroundDrawingCallback().

I also have a "TitleScreen" class that I instance when I move to the title screen.

I tried adding a setBackgroundDrawingCallback() to it's init function, but realized that the function is creating a new sprite, rather than reconfiguring some global background variable/configuration.

So I'm also now realizing, that every time I load a new level, I'm creating another BG sprite!

How should I handle this?

Is there an easy way to remove all background sprites?


Ok, I think I probably know the answer to this.

Assign the function call to a variable, then you can remove it or whatever else you want to do.

1 Like

Don't worry about old sprites hanging around — the garbage collector will free up that space when needed. But, yes, you can store the return value of setBackgroundDrawingCallback() if you want to refer to the background sprite later (or just remove it without setting a new background).

Instantiating sprites or other objects excessively or repeatedly (say, every frame or in a tight loop) can cause performance problems, but if you're only doing it once when loading levels or changing screens, it's probably not going to matter.