SpriteRenderer tries to use shader before it's loaded

There are a few different settings on SpriteManager that result in a call to SpriteRenderer._createEffects to rebuild the shader. However, the shader is first initialized in the SpriteRenderer constructor asynchronously, so there is a race condition. My code fails consistent when I construct all 15 SpriteManagers and setting pixelPerfect to true on the following line. Experimenting with a locally modified Babylon.js, the following test for _shadersLoaded inside _createEffects fixed the issue for me.

image

I’m not sure how to repro this in a playground, since it seems to require a good bit of async initialization.

Is there interest in me submitting this change as a PR?

As an aside, every SpriteRenderer constructor re-initializes the shaders, without first checking if it’s required. I could recommend a small fix for that as well in the PR, if desired.

1 Like

This seems to be an issue with the pixelPerfect setter. If you call it just right after you create a SpriteManager instance it calls the _createEffects functions however there is no guarantee that the async part of the constructor already finished.

In addition to this fix:
@Deltakosh @sebavan @Evgeni_Popov I would recommend to add pixelPerfect: boolean or options: { pixelPerfect: boolean } (as this seems to be a quite common option) to the constructor as well so we can create an SpriteManager instance with this option already set to true. Thus we save the second call to the _createEffects function.

1 Like

please! I love when community helps!

1 Like

Yes that is also a second good option (in addition!)

1 Like

Ok, lets go with the options object so we can add more options in the future.

1 Like

Here we go:

Here’s the remaining fix:

1 Like