Search code examples
c#shaderhlsl

Unity - modify shader variables from inside the shader


I have a shader, which puts a pattern (from texture) over the material:

...
    float2 patternxy = {_PatX, _PatY}; //_PatX & _PatY from inspector
    float4 pattern = tex2D(_PatTex, i.uv + patternxy);
...
    //adjust brightness depending on pattern strength and pattern map
    if (all(pattern.rgb) == 1) { color.rgb += float3(_PatternStr, _PatternStr, _PatternStr); }
...

Now I want to let the pattern scroll over the material, for that I already created a script:

public class PatternMover : MonoBehaviour
{
    new private Renderer renderer;
    private WaitForSeconds wait;

    [Range(0f, 1f)] public float delay = 0.1f;
    [Range(0f, 0.5f)] public float step = 0.005f;
    public bool ActX = true;
    public float MulX = 1f;
    public bool ActY = true;
    public float MulY = 1f;

    private void Awake()
    {
        renderer = GetComponent<Renderer>();
    }

    IEnumerator Start()
    {
        while (true) 
        {
            wait = new WaitForSeconds(delay);
            Move();
            yield return wait;
        }
    }

    private void Move()
    {
        if (ActX == true)
        {
            var x = renderer.material.GetFloat("_PatX");
            if (x <= 128) { renderer.material.SetFloat("_PatX", x + step * MulX); } else renderer.material.SetFloat("_PatX", 0);
        }
        if (ActY == true)
        {
            var y = renderer.material.GetFloat("_PatY");
            if (y <= 128) { renderer.material.SetFloat("_PatY", y + step * MulY); } else renderer.material.SetFloat("_PatY", 0);
        }
    }
}

This works absolutely fine. My problem is, that I want to use this shader on a VRChat Avatar, which means, I can't upload custom scripts. So is there a way of getting the same effect from inside the shader itself, without an additional script?

Thanks in advance


Solution

  • I fixed it another way. Instead of modifying the variables every pass, I just added Unity's _Time variable to the _PatX and _PatY variables...

    float2 patxy = {_PatX + (_Time[2]/_TimeDec)*_PatSpdX, _PatY + (_Time[2]/_TimeDec)*_PatSpdY};
    

    It was as simple as that.