Scene.onNewMaterialAddedObservable exposes not fully initialized materials


Not exactly a bug but I feel like this is a bit of a flaw in the architecture.

The materials are designed in a way that they are added to the scene in the base Material constructor.
This causes the scene.onNewMaterialAddedObservable to report materials that are not fully initialized. So it is very easy to write code that looks perfectly normal and TS agrees about that but it throws errors.
PG with such example.

Maybe that’s the case in some other classes. My suggestion is that materials (and other entities) should be added to the scene after they are fully defined.

That’s a good observation!

This callback is triggered when the material was added to the scene during construction (defined in the baser material class), but before the constructor of the actual class is done. A single frame afterwards the material is ready.
Architecture-wise, this is correct - the observable is triggered on the Material object and does not guaranty that the PBR data will be available, but that’s me just being nit-picky. I totally understand what you are saying, and totally get why you find it uncomfortable.

On event triggered in the constructor will be incorrect. I think that what we are actually missing is onMaterialReady observable in the material class. Would that solve your issue?


Yeah. That will be an alternative way to achieve something like what I do in the PG.

Still I feel like the base Material class constructor might be relevied of the duty of adding itself to the scene cause… you know, when something is added to the scene I expect it to be fully initialized. Maybe this can be done in some sort of callback or a method that is called after all the constructors with a decorator or something like that.

Dunno if I make it clear.

1 Like

We have a PR up to discuss this now: call the onNew observables when the elements are constructed by RaananW · Pull Request #13075 · BabylonJS/Babylon.js (