How do i get a shader to affect every object with the same material?
Hi!
I'm trying to implement a shader that affects all objects with a certain material. The basic idea is to have a GameObject Blurrer with a script that sets the radius and position for the shader, like so:
The rock and tree and the area around them is blurred!
Everything in the scene has the same material applied.
My first approach was to have two variables in the shader for radius and position, which i update from a script attached to the Blurrer object:
void Update ()
{
renderer.material.SetVector("_BlurPos", this.transform.position);
renderer.material.SetFloat("_BlurRadius", 200);
}
The blurrer object would be under both the Rock GameObject and the Tree GameObject in the example. The problem was that the shader only affects pixels within the object sprite itself, so the result was something like this:
Rock and Tree are blurred within radius, but the surrounding area is not
Looks like a shader only iterates over the pixels within the sprite of the particular renderer. My workaround was to have global variables in the shader, which hold the position and radius of all Blurrer GameObjects and they would add themself to this list:
//BlurScript.cs
private static List<Vector4> blurPositions= new List<Vector4>(10);
private static int index = -1;
void Start ()
{
Shader.SetGlobalVectorArray("G_BlurPositions", blurPositions);
index++;
}
void Update()
{
blurPositions[index] = this.transform.position;);
Shader.SetGlobalVectorArray("G_BlurPositions", blurPositions);
}
void OnDestroy()
{
blurPositions.RemoveAt(index);
Shader.SetGlobalVectorArray("G_BlurPositions", blurPositions);
index--;
}
I was able to get the solution working as each instance had access to all the positional data. However, this solution feels very hacky and I have no idea how to get a dynamic size array for a shader (currently using uniform float4 G_BlurPositions[10] ) I am new to writing shaders and would like some help with this issue:
Are shaders even the right thing to use in implementing something like this? Are there other options?
Is there any other mechanism for sharing data between shaders? In my case positions and radiuses.
What is the usual way of implementing something like this?
Your answer
Follow this Question
Related Questions
Getting Color Generated from Shader to Script to Shader 0 Answers
Very basic shader problem 0 Answers
Converted ShaderToy shader showing up black 1 Answer
why outline is drawed only on front side of skinned mesh render 1 Answer
Render oject A when behind object B, but not if behind object B and object C 1 Answer