Dynamically changing materials parameters in script

Godot Version

4.4/4.5

Question

When i put a material on two different meshes i have to make one unique to change the textures and parameters - is it possible to dynamically change the material parameters in script for the same result?

Hi,

Have a look at set_shader_parameter function. That function takes two parameters: the shader parameter name, and the value you want to assign.
For instance:

material.set_shader_parameter('some_value', 45)
1 Like

So referring to the section in the help page:

Note: Changes to the shader uniform will be effective on all instances using this ShaderMaterial. To prevent this, use per-instance uniforms

So if they get set in process() or physics_process() they will only take the parameters from the most recent shader material? Can they be set up in a draw() function?

Also the objects are not instances, so im not sure what would happen if i use the per instance uniforms…

I believe you can set the parameters from anywhere, although I would avoid doing it every frame if possible. Should be okay performance wise if you have to.

Also the objects are not instances, so im not sure what would happen if i use the per instance uniforms…

Well, you should give it a try as it’s definitely something that seems a good fit for your use case.
What you could also do is using the duplicate() function to duplicate a material at runtime, creating a new instance that you can set the parameters of.

I think i will probably create a copy of the materials that id like to repeat, then i can run some tests on setting parameters to see whether the frame rate is affected.

1 Like