Search code examples
c#unity-game-engineshadershader-graph

Unity: trying to set a global shader property using .SetGlobalFloat


Im creating a 3d game in Unity, basically, I have a shader that the in game scanner uses, multiple things are scannable meaning there are multiple materials with the same shader. This shader is created using shader graph.

I want to globally modify a property in the shader across all materials that use it.

This is the line I am trying to use to modify the property:

void FixedUpdate()
{
    if(Input.GetMouseButton(1))
    {
        scannableMat.shader.SetGlobalFloat("_offset", 2);
    }
}

However I get this error:

Member 'Shader.SetGlobalFloat(string, float)' cannot be accessed with an instance reference; qualify it with a type name instead (CS0176)

I have tried disabling the exposed setting but that didn't work. Im pretty new to shadergraph so I dont know if what I want it to do is possible, however any work around that achieve the same thing would be appreciated. Sorry if this is an easy fix, thanks in advance.


Solution

  • First of all, note that it doesn't make sense to set a "Global Float" for a single material.

    Probably what you are looking for is really only scannableMat.SetFloat("_offset", 2). However, if your material is an instance of the original material, this wouldn't work and setting a global shader value would be a better option.

    If you have a reference for a MeshRenderer and your materials are not instances, you can use meshRenderer.sharedMaterial.SetFloat("_offset", 2).

    Lastly, if you really want to set a global value for all shaders, try Shader.SetGlobalFloat("_offset", 2).