GLSL shaders for Unity 3d – Flat color

Suppose you wanna make a shader that displays any color instead of red only. You need to pass somehow this information from the Unity Editor to the shader. In this article we will use shader properties and a special type of glsl variables, uniforms.

The first thing to do is to add an option to select a color from Inspector view. To do so, we will modify the Properties code from the previous post. It will become

Properties
{
       // This allows to choose the color from the Editor
       _Color ("Main Color", Color) = (1,0.5,0.5,1)
}

Ok,now if we select the shader in the inspector, we can choose a color. To pass this color in the shader we will change the fragment code as follows :

#ifdef FRAGMENT
	// This is a way to pass the data from the Unity Editor to the shader, via uniforms
	uniform vec4 _Color ;
	void main()
	{
	   gl_FragColor = _Color;
	}
#endif

So the complete code of the shader will be :


 

Shader "simple_Color_Shader"
{
	Properties
	{
	       // This allows to choose the color from the Editor
	       _Color ("Main Color", Color) = (1,0.5,0.5,1)
	}
	SubShader
	{
		Tags { "Queue" = "Geometry" }
		Pass
		{
		GLSLPROGRAM
		#ifdef VERTEX
			void main()
			{
			   gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
			}
		#endif  

		#ifdef FRAGMENT
			// This is a way to pass the data from the Unity Editor to the shader, via uniforms
			uniform vec4 _Color ;
			void main()
			{
			   gl_FragColor = _Color;
			}
		#endif
		ENDGLSL
		}
	}
}

And that is all ! References from the first part still apply.

This entry was posted in Uncategorized by ippo. Bookmark the permalink.

Leave a Reply