How to change the property of a shader itself? (not the material)

Hi,

I found tutorials on how to change the property of a material applied to a game object, but how would you change the property of the shader itself on runtime.

First use case:
100 game objects in a scene, each one with it’s own material, and all the materials share the same shader. How would you change the property for all the objects at once on runtime?
I thought I’d change the property of the shader itself, but I don’t know how to do that. Or is there another way to do that?

Second use case (more general):
How would you do to change a variable in a script and it would affect automatically all the shader that has a property with the same name than that of the variable?
The reason I am asking this is because there are many shaders that should be impacted by the variation of a certain variable, and new shaders that will be created by other members of the development team should too.
It would be much easier to have the shaders ‘‘feed’’ on that variable than modify the script each time to add a new shader that was created by an artist.

Thank you!

Hi!

Why on earth would you have 100 different materials sharing the same shader, if you want them all to have mostly the same properties? Wouldn’t it be much simpler (and faster) to just use the same material? :eyes:

Keep in mind that using different materials breaks batching. 100 objects using 100 materials generally mean 100 draw calls. 100 objects using the same material would result in just 1 drawcall (depending on your dynamic/static batching setting), which is much more efficient.

You can use the same material for all objects, and change specific properties for each one using MaterialPropertyBlocks. This is much more efficient than using a unique material for each object, since it still allows for batching.

This article might be useful:
https://thomasmountainborn.com/2016/05/25/materialpropertyblocks/

You can use global properties, and then set them at runtime using Shader.SetGlobalXXX:
https://docs.unity3d.com/ScriptReference/Shader.SetGlobalFloat.html

There’s also Shader.SetGlobalVector, SetGlobalTexture, etc. These will affect all shaders that use that property.

I cannot use one material for all the assets in my scene. I have different materials because I have different assets (then each asset is instantiated, and the batching will work for those instances). Basically, there are some variables that are part of the gameplay. Depending on how the player plays, the values of these variables will change on runtime and that will affect many different objects (and their instances) in the whole scene.

That’s what I was looking for! Thank you!