shader outline in csharp

To create a shader outline effect in C#, you can use a combination of rendering techniques and shaders. Here are the general steps to create a basic outline effect:

  1. Render the object with the normal materials and shaders.
  2. Create a second camera that only renders the outline of the object.
  3. Use a custom "outline shader" on the second camera that detects edges and draws only the edges of the object in a contrasting color.
  4. Combine the two renders, adjusting transparency if necessary, to create a final image with an outline effect.

Here's an example of a very basic outline shader in Unity:

main.cs
Shader "Custom/OutlineShader" {
    Properties {
        _MainTex ("Texture", 2D) = "white" {}
        _OutlineColor ("Outline Color", Color) = (0,0,0,1)
        _OutlineWidth ("Outline Width", Range(0.0, 0.1)) = 0.001
    }

    SubShader {
        Tags {"Queue"="Transparent" "RenderType"="Opaque"}

        Pass {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct appdata {
                float3 vertex : POSITION;
            };

            struct v2f {
                float4 pos : SV_POSITION;
            };

            float _OutlineWidth;
            float4 _OutlineColor;

            v2f vert (appdata v) {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target {
                float depth = LinearEyeDepth(tex2D(_CameraDepthTexture, i.pos.xy));
                float4 depthPos = ComputeGrabScreenPos(i.pos.xy, depth);
                float4 col = tex2Dproj(_MainTex, UNITY_PROJ_COORD(depthPos));

                float4 outlineCol = tex2Dproj(_MainTex, UNITY_PROJ_COORD(depthPos + float4(0, _OutlineWidth, 0, 0)));
                outlineCol += tex2Dproj(_MainTex, UNITY_PROJ_COORD(depthPos + float4(0, -_OutlineWidth, 0, 0)));
                outlineCol += tex2Dproj(_MainTex, UNITY_PROJ_COORD(depthPos + float4(_OutlineWidth, 0, 0, 0)));
                outlineCol += tex2Dproj(_MainTex, UNITY_PROJ_COORD(depthPos + float4(-_OutlineWidth, 0, 0, 0)));
                outlineCol *= _OutlineColor;
                outlineCol /= 4;

                return lerp(col, outlineCol, col.a);
            }
            ENDCG
        }
    }
}
1756 chars
52 lines

To apply this shader to an object in Unity, you can create a new material using this shader and assign it to the object. You can then adjust the properties of the material to adjust the thickness and color of the outline.

gistlibby LogSnag