- Home /
optimising shaderlab code and using properties variable
i've written a shader using shaderlab, that has a solid color on top of a texture and as the alpha for the solid color gets lower, the color and the texture blend together, leaving only the texture when alpha is 0. Here is the code:
Shader "Custom/colorToOpaqueShader" {
Properties {
_MainTex ("main texture", 2D) = "white" {}
_Color ("Color",Color) = (1,1,0,1)
_ColorOpacity("Color Opacity",Float) = 1
}
SubShader {
Pass
{
SetTexture[_MainTex]
}
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
Material
{
Diffuse (1,1,1,.2)
}
Lighting On
}
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
Material {
Diffuse [_Color]
}
Lighting On
}
}
}
First pass sets the texture, second pass adds a diffuse to the texture and the third pass sets out the color on top.
First question:
i would like to be able to control the color opacity using only a variable, not setting the entire color.
i.e. in the third pass i would like to have something like this:
Diffuse(_Color.r,_Color.g,_Color.b,_ColorOpacity)
But 1) i can't get _Color.r using this sintax and 2) Although i have _ColorOpacity declared in properties, it doesn't seem to be usable (can't be recognized by unity)
Second question:
I haven't ever written a shader until today and was wondering how can i optimise this code.. 3 passes shoulds like a lot for such a small effect, i'm sure it could have been written in 1.
Third question:
How can i declare iterators in Shaderlab? i would like to have a int file that grows every frame, and have the opacity set something like
Diffuse (.2,.2,.2, (i%40)/40)
I know i can set a variable from scripts, but i would like this functionality to be incorporated directly in a shader.
Note: If it is at your disposal, including a CG code example of this functionality would be great. I would like to start learning both shaderlab and cg to have a better grasp of the concepts
Answer by Julien-Lynge · Jan 30, 2013 at 03:18 AM
Sorry, you have way too many questions for a single question. Please post them individually.
I'll try to answer what questions I can:
First, you can set the alpha separately with texture combiners. See this page:
http://docs.unity3d.com/Documentation/Components/SL-SetTexture.html
and look for Separate Alpha & Color computation.
/////////////////////////////////////////////////////////
If you're interested in learning Cg, here are some resources:
http://en.wikibooks.org/wiki/Cg_Programming/Unity
http://www.gamedev.net/topic/600658-best-place-to-start-shader-programming/
If you want to learn more about ShaderLab (the code you posted), this is a great set of tutorials: