Different texture per mesh instance using instance buffers?

Hello.
I’d like to know if it’s possible to create instances of a mesh, but have a different texture on each instance?
I know that this is possible with mesh copies, but we’d have to take a big performance hit.

We can change the color on a per instance basis using Instanced Buffers, so I was wondering if this would also work with textures.
I kind of asked this before as an additional question to another thread and got an answer from @Deltakosh, however now that I’m trying to actually implement it I’m struggling.

You can instantiate any attributes supported by the shaders (typically: color, uv, uv2, etc…)
If you create your own shader with ShaderMaterial it could be anything declared as an attribute

Does this also mean we can change the texture with this? And if so, how?
Because it seems that we can only pass a pair of floats to me.

I prepared a simple playground with the buffers for color working and 2 textures loaded in as a starting point.
https://www.babylonjs-playground.com/#64K1I1#1

I think what you can do is adding an offset to the uv coordinates of each instance:

https://www.babylonjs-playground.com/#64K1I1#2

So, you will need to have a single texture that is the merging of the two textures and use an appropriate offset to render the right part of the texture on the 2nd instance.

1 Like

@Evgeni_Popov

Thank you for the great answer!
So we can use a texture atlas and then just change the UVs.

This would work great in most cases, but in our case we want to also enable users to upload their own custom textures and use them and there might also be frequent updates to the textures we provide so that makes it really hard to implement :thinking:

You can use a DynamicTexture to create the texture and for fast updates.

1 Like