- Home /
Change Color Based On Pixel X Coordinate in Shader
Essentially I'm trying to achieve the effect that you see on a loading bar but for a more complex sprite shape. I think the best solution for this would be a shader.
The basic idea of what I am trying to understand how to make is this:
Lets say we have a Texture2D and an input value which is a float that ranges from 0 to 1.
If the input value is 0.5 then the left half of the Texture2D would be one color while the right half would be another color.
Thanks!
Answer by Layer-10 · Apr 27 at 09:10 PM
After a few more hours of research I have learned more about the way that the shader language works in Unity.
I found that I can access the pixel coordinates using the i.uv.x and i.uv.y in the frag function so the solution was just as simple as using some if statements to compare the value of those coordinates to my float property and manipulate the col.r, col.g, col.b, and col.a.
I found that my image has to be perfectly square for the coordinate proportions to work the way I want but that isn't really an issue for me.
I used these two very informative youtube videos which give a basic overview and examples of how to manipulate textures. I'm leaving these videos here for others who may stumble across this topic with the same level of confusion that I had.
Unity Tutorial: A Practical Intro to Shaders
Code Example
Top Left: Shader Properties
Top Right: Material Inspector
Bottom Left: Shader frag Function
Bottom Right: Result
Ensure to also add the property to your Pass{}: