Reusing materials for performance

Hello Forum,
When looking at my Scene in Inspector, I notice that many materials are instantiated multiple times. I suspect this has some effect on the load time of my application. For example, the wall material I am using is listed 30-40 times (once for every wall I am creating in my Scene I guess). Or am I wrong and Babylon is able to reuse the same material and herefore only loading it once…?

Currently, I am creating the walls in the following way…

For every wall in my apartment, I am creating actual surfaces:

this.apartment.wallSurfaces.forEach(wallSurface => this.createWallSurface(wallSurface));

In the createWallSurface function, I am creating actual meshes for the walls:

createMeshForWallSurface(wallSurface, wallSurfaceParent, wallOpeningCSGs, this.getScene());

Within the creation of the actual mesh, I am also adding a material to the wall:

mesh.material = createMaterial('wall', scene);

It seems logical to me that this procedure results in many instantiations of the same material file. My Question is, is there an efficient way to use the same material for all the meshes? Maybe in a way that the material is first instantiated and later applied to all the wall meshes in one go. Ormight his not even be a problem for my performance and load time because babylon is somehow smart and not loading the same texture over and over again?

Thank you once again for your amazing input and have a nice day :slight_smile:

Yes, you should first create the material outside your loop and simply assign it to all your meshes.

Note that if the materials all use the same textures, they won’t be reloaded / recreated, but creating 50+ of the same material is still a waste of JVM memory and CPU.


Thank you, I’ll try to implement it as such.

Just a quick update on this topic in case someone stumbles over it…
I ended up having to create a material with the same texture for every single wall since the walls have different dimensions and the wall-texture has to be scaled for every wall separately.