Same material and different shader uniforms

Hi,
I have several mesh instances which use the same material. Is it possible to set different shader uniforms for each mesh instance or do I have to use unique material for each mesh instance?

I’m trying to do it as follow, but it doesn’t work.

let entities: pc.Entity[];

// Create entities (each entity's model use the same material)

entities[0].model.meshInstance[0].material.setParameter("uColor", [1, 0, 0]);

// Unfortunatelly, now all entities use uColor se to [1, 0, 0]

I think I have to set the uniform value for each instance every frame before it’s going to be rendered. But how to do that?

Hi @NokFrt,

Yes, you can definitely override the uniforms per mesh instance, independently of the material.

Just use the setParameter method directly on the mesh instance:

entities[0].model.meshInstance[0].setParameter("uColor", [1, 0, 0]);
3 Likes

Hi @Leonidas, thank you very much. I knew I have to set the parameter directly on the mesh instance but I set it on it’s material instead. My mistake.

1 Like

Is there a performance issue having a single (custom) material and override by set Parameter rather than have several materials for objects that do share their uniforms?

Hi @plasmalasgun,

That’s a valid question. Playcanvas will make sure to group all materials that share the same parameters into a single compiled shader. So you can have multiple materials that share the same properties, and with the convenience that brings without any significant performance hit.

Additional materials only increase slightly the loading time (since they are a separate .json file), though its size is very small.

2 Likes

So even if you have different materials with different uniforms… can you still use the same shader instance and share it across materials?

So, this depends on the kind of uniforms if they trigger/require additional shader chunks.

For example:

  1. Two materials with different diffuse/opacity textures will still use the same shader program. Since they both require the same shader chunks. A single shader program is generated.

  2. Two materials with different diffuse/opacity textures and one of them having diffuse tint or vertex color enabled. Two different shader programs are generated.

1 Like