Creating a Wireframe Shader in Unity
Why Use a Wireframe Shader?
A wireframe shader can be useful in various situations, such as:
- Prototyping
- Creating a cybernetic or AR feel for an object
- Creating a net-like material
- Visualizing the wireframe shapes of objects
Project Setup
To get started, create a new 3D project in the Unity Hub and set up the following folders:
- Materials
- Shaders
- Images
Creating the Shader
In the Shaders folder, create a new Unlit Shader and name it Shader_Unlit_WireframeShader
. Double-click the shader to open it in your preferred code editor.
Defining the Shader Properties
In the shader properties, add variables for the wireframe’s front, back, color, and width. We’ll also change the Queue
to Transparent
and set the Blend
to SrcAlpha OneMinusSrcAlpha
.
Properties {
_FrontColor("Front Color", Color) = (1, 1, 1, 1)
_BackColor("Back Color", Color) = (1, 1, 1, 1)
_WireWidth("Wire Width", Float) = 1.0
}
Creating the Shader Passes
We’ll create two passes for this shader: one for forward-facing triangles and one for back-facing triangles.
Forward-Facing Triangles
In the first pass, we’ll use Cull Back
to remove back-facing triangles. We’ll define a custom geometry function to add barycentric coordinates to each triangle.
Pass {
Cull Back
CGPROGRAM
#pragma vertex vert
#pragma geometry geom
#pragma fragment frag
...
Barycentric Coordinates
We’ll create a struct to house the barycentric coordinates of the triangles and add a position variable.
struct BarycentricCoords {
float3 position;
float3 barycentric;
};
Geometry Function
The geometry function will process one triangle at a time, passing through the position of the vertices and populating the barycentric variable.
[maxvertexcount(3)]
void geom(triangle vertex v[3] : SV_POSITION, inout TriangleStream<BarycentricCoords> stream) {
...
}
Fragment Shader
In the fragment shader, we’ll make the pixel white if it’s close to the edge and more transparent if it’s further away.
float4 frag(BarycentricCoords input) : SV_Target {
...
}
Adding the Second Pass
We’ll add a second pass for back-facing triangles, using the same geometry function and fragment shader.
Pass {
Cull Front
CGPROGRAM
#pragma vertex vert
#pragma geometry geom
#pragma fragment frag
...
}
Testing the Shader
Save the shader and create a material from it. Drag the material onto an object in your scene to see the wireframe shader in action.
Tips and Variations
You can experiment with different wireframe colors, widths, and styles by modifying the shader properties and code.
By following this tutorial, you’ve successfully created a wireframe shader in Unity using ShaderLab code. You can now apply this shader to various objects in your scene to achieve a unique and stylized look.