I want a material/shader that makes an object glow (with visible outline). It needs to be URP compatible, and not require messing with rendering features or post processing stack. Unity 2022 is the target. I will add (and later remove) this material from game object render's in order to highlight a particular object that's being interacted with in-game.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Create a new material and assign the GlowShader to it.
Adjust the properties:
_BaseColor: Set to the object's original color or a bright color (e.g., white).
_GlowColor: Set to a bright color with some transparency (e.g., (1,1,1,0.5) for a soft white glow).
_GlowPower: Controls the thickness of the glow (start with 0.1 and adjust as needed).
🧪 Usage in Game
Attach this script to the object you want to highlight:
csharp
using UnityEngine;
public class GlowHighlight : MonoBehaviour
{
private Renderer _renderer;
private Material _originalMaterial;
private Material _glowMaterial;
void Awake()
{
_renderer = GetComponent<Renderer>();
_originalMaterial = _renderer.material;
_glowMaterial = new Material(Shader.Find("Custom/GlowShader"));
}
public void StartGlow()
{
_renderer.material = _glowMaterial;
}
public void StopGlow()
{
_renderer.material = _originalMaterial;
}
}
Call StartGlow() when the object is interacted with, and StopGlow() when the interaction ends.
⚠️ Notes & Limitations
Performance: This uses two draw calls per object. Avoid applying to many objects simultaneously.
Z-Fighting: Ensure _GlowPower is small enough to avoid visual artifacts.
Transparency: The glow pass uses additive blending, which works best on opaque backgrounds.
No Post-Processing: This effect is purely shader-based and doesn't require Bloom or other URP post-processing features.
This solution provides a simple, efficient glowing outline effect that works natively in URP without additional setup. Perfect for temporary highlighting in games! 🌟
User
that works ok with a cube, but fails with a meshrenderer that has multiple materials. I need to be able to apply the effect to the entire mesh.
Assistant
To apply the glow effect to a MeshRenderer with multiple materials (e.g., a character model with separate materials for clothing, skin, etc.), we need to ensure all submeshes of the object receive the glow treatment.
✅ Goal
Apply a glowing outline to the entire object, including all submeshes.
Replace each original material with a matching glow version.
Avoid visual artifacts or partial glow effects due to missing submesh materials.
Maintain compatibility with URP and Unity 2022.
No post-processing required.
🛠️ Updated Shader
The shader remains mostly unchanged. It still uses a two-pass approach:
A glow pass (scaled + additive blending) for the outline.
A base pass that renders the object with a base color (or emissive color).
hlsl
User
that works. Is there anything we can do so that the glowing lines show thru objects, like if the effect is applied to an object that is behind a wall? Again, without render features etc.
Assistant
To make the glow show through walls and occluding objects (like a "highlight through fog/walls" effect), you can modify the glow pass to ignore depth entirely and render on top of everything. This creates a "see-through" glow that remains visible even when the object is occluded.
🔧 Updated Shader (Modified Glow Pass)
Update your GlowShader.hlsl to render the glow pass in Overlay queue, ignore depth testing, and always draw on top.
hlsl
User
ok, that shows thru like it should, but instead of an subtle edge effect around the outline, it's now covering almost the entire object in white lines
Assistant
To resolve the issue where the glow unintentionally covers most of the object instead of just the edge outline, we need to refine how the glow pass renders the extruded mesh.
✅ Problem Summary
The glow pass currently extrudes the mesh outward along normals, but due to incorrect culling and blending behavior, it ends up covering the entire object rather than just the silhouette edges.
This happens because:
The glow mesh is drawn over the base mesh, even where it overlaps.
The culling mode (Cull Back) causes the glow mesh to render its front faces, which can visually fill the object instead of just outlining it.
The additive blending (Blend SrcAlpha One) adds brightness everywhere the glow mesh overlaps the base.
🛠️ Fix: Render Only the Silhouette
To achieve a clean glowing outline, we'll modify the glow pass to:
Extrude the mesh outward slightly along normals.
Cull front faces, so only the back-facing geometry (i.e., the sides of the extruded mesh) is rendered — this creates a true outline.
Adjust blending and color to make the glow subtle and edge-focused.
🧪 Updated Glow Pass (Shader Snippet)
Update the Glow Pass in your GlowShader.hlsl with the following settings:
hlsl
// --------------------------
// Glow Pass (Additive, Overlay)
// --------------------------
Pass
{
Name "Glow"
Tags { "Queue"="Overlay" "RenderType"="Transparent" }
Blend SrcAlpha One
ZWrite Off
ZTest Always
Cull Front // 👈 Render only back-facing triangles (i.e., the outline)
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
struct Attributes
{
float4 positionOS : POSITION;
float3 normalOS : NORMAL;
};
struct Varyings
{
float4 positionHCS : SV_POSITION;
};
float4 _GlowColor;
float _GlowPower;
Varyings vert(Attributes v)
{
Varyings o;
// Extrude along normal in object space
float3 positionOS = v.positionOS.xyz + v.normalOS * _GlowPower;
float4 positionWS = TransformObjectToWorld(float4(positionOS, 1.0));
o.positionHCS = TransformWorldToHClip(positionWS.xyz);
return o;
}
float4 frag() : SV_Target
{
return float4(_GlowColor.rgb, _GlowColor.a);
}
ENDHLSL
}
User
you've managed to make it slightly transparent, but it's not better. it's almost like you've inverted teh desired effect, with the surfaces shaded and the intersections not. I don't really need or want interior edges highlighted, just the outer ones.
Assistant
To achieve a clean, outer-edge-only glow/silhouette that shows through walls (like a "ghosted" outline), we need to shift from a normal-extrusion approach to a stencil buffer-based outline. This method avoids filling surfaces or highlighting internal edges, and instead highlights only the outer silhouette — even when the object is occluded.
✅ Goal
Only the outer edges of the object glow.
Glow shows through occluding objects (e.g., walls).
No post-processing or advanced render features.
Compatible with URP and Unity 2022.
Works with multiple materials/submeshes.
🧠 Why This Works
We'll use the stencil buffer to:
Render the object to the stencil buffer.
Render a scaled-up version of the object afterward, but only where the stencil buffer does not contain the object — i.e., its outline.
This method ensures:
Only the silhouette is rendered.
Interior edges are ignored.
The glow can be made visible through walls by disabling depth testing.
🛠️ Updated Shader (Stencil-Based Outline)
Create a new shader called SilhouetteOutlineShader.hlsl:
hlsl
User
that's pretty close to what I want, but is it possible to make it so that the added lines are occluded by the object itself, just not the rest of the world? I'm able to see the front and back of the object which looks pretty weird.
Assistant
To achieve a clean outer-edge glow that:
Is occluded by the object itself (no self-overlap),
Shows through other objects (e.g., walls),
And avoids internal edges or double-sided glow,
We'll use a hybrid approach combining:
Normal extrusion for a clean outline,
Stencil buffer to exclude the object's interior,
Cull Front to render only the outer edge,
Overlay queue to render on top of everything.
🧪 Updated Shader (Stencil + Normal Extrusion)
hlsl
User
that's pretty close to what I want, but is it possible to make it so that the added lines are occluded by the object itself, just not the rest of the world? I'm able to see the front and back of the object which looks pretty weird.
Assistant
To achieve a silhouette outline that is occluded by the object itself (so it doesn’t show through the front/back of the object) but still visible through walls and other objects, we need to refine the stencil + depth buffer technique used in the previous shader.
✅ Goal
Outline is only visible on the outer silhouette.
Outline is occluded by the object itself (no front/back glow).
Outline shows through walls and occluders.
No post-processing or advanced render features.
Compatible with URP and Unity 2022.
Works with multiple materials/submeshes.
🧠 Key Technique: Depth Buffer Comparison
We'll use a depth buffer comparison trick to make the outline:
Only draw where it is behind the object's own geometry (i.e., silhouette).
Ignore depth from other objects, so it shows through walls.
This is done using:
ZTest Greater: Only draw the outline where it is behind the object's front-facing geometry.
Cull Front: Ensures only the back-facing geometry (i.e., silhouette) is rendered.
ZWrite Off: Prevents interfering with depth buffer.
Blend SrcAlpha One: Gives a glowing look.
🛠️ Updated Shader (Silhouette with Depth Occlusion)
hlsl
User
that compiles but now there's no effect, ie no outline or anything
Assistant
The issue likely stems from incorrect depth buffer behavior in the outline pass. When using ZTest Greater, the outline will only render if it’s behind the original object. However, if the outline mesh is scaled forward (closer to the camera), this test fails — resulting in no visible outline.
🔧 Solution: Adjust Depth Behavior
We'll make the following key fixes:
Use ZTest Less to ensure the outline renders only in front of the object (but behind walls).
Disable depth writing (ZWrite Off) to avoid interfering with the scene.
Render the outline in the Transparent queue to ensure proper blending.
Adjust scaling direction to ensure the outline expands outward consistently.
✅ Fixed Shader Code
hlsl
User
so far this was the best effect of all that's been done, but it still renders lines too think, and doesn't self occlude: Shader "Custom/SilhouetteGlow"
{
Properties
{
_OutlineWidth ("Outline Width", Range(0, 0.1)) = 0.03
_OutlineColor ("Outline Color", Color) = (1,1,1,1)
_OccludedAlpha ("Occluded Alpha", Range(0, 1)) = 0.3
}
code
SubShader
{
Tags { "RenderType"="Transparent" "Queue"="Transparent" "RenderPipeline"="UniversalPipeline" }
// Outline pass - only the silhouette
Pass
{
Name "SilhouetteOutline"
Tags { "LightMode"="SRPDefaultUnlit" }
Cull Front
ZWrite Off
ZTest Always
Blend SrcAlpha OneMinusSrcAlpha
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
struct Attributes
{
float4 positionOS : POSITION;
float3 normalOS : NORMAL;
};
struct Varyings
{
float4 positionHCS : SV_POSITION;
float3 normalWS : TEXCOORD0;
float3 viewDirWS : TEXCOORD1;
};
CBUFFER_START(UnityPerMaterial)
float4 _OutlineColor;
float _OutlineWidth;
float _OccludedAlpha;
CBUFFER_END
Varyings vert(Attributes input)
{
Varyings output;
VertexNormalInputs normalInputs = GetVertexNormalInputs(input.normalOS);
VertexPositionInputs positionInputs = GetVertexPositionInputs(input.positionOS.xyz);
// Only expand along normals that face away from camera (silhouette edges)
float3 viewDirWS = GetWorldSpaceViewDir(positionInputs.positionWS);
float3 normalWS = normalInputs.normalWS;
// Expand the vertex position
float3 expandedPositionWS = positionInputs.positionWS + normalWS * _OutlineWidth;
output.positionHCS = TransformWorldToHClip(expandedPositionWS);
output.normalWS = normalWS;
output.viewDirWS = viewDirWS;
return output;
}
half4 frag(Varyings input) : SV_Target
{
// Fade outline based on viewing angle to reduce interior edge visibility
float3 normalWS = normalize(input.normalWS);
float3 viewDirWS = normalize(input.viewDirWS);
float viewDot = abs(dot(normalWS, viewDirWS));
// Only show outline on edges that are more perpendicular to view
float edgeFactor = 1.0 - smoothstep(0.2, 0.8, viewDot);
half4 color = _OutlineColor;
color.a *= _OccludedAlpha * edgeFactor;
return color;
}
ENDHLSL
}
}
Assistant
To achieve a clean, self-occluding silhouette outline that shows through walls but doesn’t render on the front/back of the object itself, we’ll refine your existing shader with:
This version handles all materials on the object, ensuring that every submesh gets a glow version.
csharp
using UnityEngine;
public class GlowHighlight : MonoBehaviour
{
private Renderer _renderer;
private Material[] _originalMaterials;
private Material[] _glowMaterials;
[SerializeField] private Color glowColor = new Color(1, 1, 1, 0.5f);
[SerializeField] private float glowPower = 0.1f;
void Awake()
{
_renderer = GetComponent<Renderer>();
_originalMaterials = _renderer.materials;
_glowMaterials = new Material[_originalMaterials.Length];
for (int i = 0; i < _originalMaterials.Length; i++)
{
Material original = _originalMaterials[i];
Material glowMat = new Material(Shader.Find("Custom/GlowShader"));
// Copy base color from original material
glowMat.SetColor("_BaseColor", original.HasProperty("_BaseColor") ? original.GetColor("_BaseColor") : Color.white);
glowMat.SetColor("_GlowColor", glowColor);
glowMat.SetFloat("_GlowPower", glowPower);
_glowMaterials[i] = glowMat;
}
}
public void StartGlow()
{
_renderer.materials = _glowMaterials;
}
public void StopGlow()
{
_renderer.materials = _originalMaterials;
}
private void OnDestroy()
{
// Clean up dynamically created materials
foreach (Material mat in _glowMaterials)
{
if (mat != null) Destroy(mat);
}
}
}
🧠 Key Notes
_renderer.materials is used instead of _renderer.material to handle multiple submesh materials.
Each glow material is instantiated separately to avoid unintended sharing between submeshes.
The base color is copied from the original material (if available) to maintain visual consistency.
You can adjust glowColor and glowPower via the Inspector to fine-tune the effect.
🧪 Usage
Attach the GlowHighlight script to any object with a MeshRenderer.
Assign the GlowShader to a new material and ensure it's in the Custom/GlowShader path.
Call StartGlow() to enable the glowing outline, and StopGlow() to disable it.
🚫 Limitations & Considerations
Textures: This shader does not support textures in the base pass. If needed, extend the shader to sample textures from the original materials.
Performance: Each submesh adds a draw call. Use sparingly for performance-critical cases.
Z-Fighting: Adjust _GlowPower carefully to avoid flickering or overlapping geometry issues.
✅ Result
With this setup, your object—regardless of how many materials it uses—will glow uniformly with a visible outline. This works seamlessly in URP and is ideal for temporary highlighting (e.g., hover effects, focus states).
Ignores depth buffer, draws glow regardless of occlusion
ZWrite
Off
Doesn’t write to depth buffer, avoids interfering with other objects
Cull
Back
Ensures glow wraps the object correctly
Blend
SrcAlpha One
Additive blending for glowing effect
🧪 Script Update (Optional)
No changes needed to the script unless you want to expose glow color/power via Inspector (already handled).
🧠 How It Works
The glow pass is rendered last (due to Queue="Overlay"), drawing on top of all other geometry.
By disabling depth testing (ZTest Always), it ignores occlusion and appears even if the object is behind walls or other objects.
The base pass still renders normally (with depth), so the object itself is occluded, but the glow remains visible.
✅ Result
The glowing outline will always be visible, even when the object is behind walls, doors, or other geometry.
No need for complex render features (like depth pre-passes or custom renderers).
Works seamlessly with URP and Unity 2022.
⚠️ Limitations
Performance: The glow pass is drawn unconditionally, so avoid applying to many objects simultaneously.
Perspective Issues: The glow may appear slightly misaligned at extreme viewing angles due to lack of depth-awareness.
UI Overlap: Since it uses the Overlay queue, it may render over UI elements. You can adjust the draw order if needed.
🧪 Example Use Case
Highlighting a hidden enemy behind a wall in a stealth game.
Showing a collectible item through terrain in an open-world game.
Indicating an interactable object behind obstacles.
With this approach, you get a "ghost-like" glow that pierces through walls — perfect for temporary visual cues in gameplay! 🔥
🎨 Visual Tuning Tips
Reduce _GlowPower to a smaller value (e.g., 0.02–0.05) to avoid excessive extrusion.
Tweak _GlowColor to be more subtle — e.g., new Color(1, 0.5f, 0, 0.3f) for a soft orange glow.
Consider using a non-additive blend mode like Blend One OneMinusSrcAlpha if additive is too bright.
🧠 Why This Works
By culling front faces (Cull Front), the GPU only draws the sides of the extruded mesh — which form the outline. This avoids filling the center of the object with glow.
Using ZTest Always and Queue="Overlay" ensures the glow appears on top of everything, even occluded objects, while only showing the edge of the object.
✅ Result
After applying these changes:
The glow will now appear as a thin, consistent outline around the object.
The glow will still show through walls and occluders.
The base mesh remains visible underneath, preventing the object from looking washed out or fully white.
🧪 Optional: Add Depth Offset to Avoid Z-Fighting
To further improve visual stability, you can slightly offset the glow mesh in screen space using the fragment shader:
hlsl
float4 frag() : SV_Target
{
// Push slightly into screen space to avoid Z-fighting
float depth = LoadCameraDepth(ScreenPos.xy / ScreenPos.w);
float depthDiff = abs(ComputeLinearEyeDepth(depth, false) - ComputeLinearEyeDepth(Input.positionHCS.w, false));
clip(-depthDiff); // Only render if behind existing geometry
return float4(_GlowColor.rgb, _GlowColor.a);
}
This ensures the glow only renders where it's behind the base mesh, enhancing the silhouette effect.
🚫 Limitations
Complex Meshes: Highly detailed or concave meshes may still show partial glow coverage.
Perspective Distortion: At steep angles, the glow may appear stretched.
Performance: Still two draw calls per object; avoid overuse.
🧩 Summary
Fix
Purpose
Cull Front
Renders only the outline, not the full mesh
ZTest Always
Ensures glow shows through walls
Blend SrcAlpha One
Creates a glowing effect
Small _GlowPower
Prevents over-extrusion and maintains outline fidelity
With these adjustments, your glow effect becomes a clean, see-through outline, ideal for highlighting interactable or important objects in-game. 🔥
This script replaces all materials with the silhouette shader version:
csharp
using UnityEngine;
public class SilhouetteHighlight : MonoBehaviour
{
private Renderer _renderer;
private Material[] _originalMaterials;
private Material[] _outlineMaterials;
[SerializeField] private Color outlineColor = new Color(1, 0.5f, 0, 0.5f);
[SerializeField] private float outlineThickness = 1.02f;
void Awake()
{
_renderer = GetComponent<Renderer>();
_originalMaterials = _renderer.materials;
_outlineMaterials = new Material[_originalMaterials.Length];
for (int i = 0; i < _originalMaterials.Length; i++)
{
Material outlineMat = new Material(Shader.Find("Custom/SilhouetteOutlineShader"));
outlineMat.SetColor("_BaseColor", _originalMaterials[i].HasProperty("_BaseColor") ? _originalMaterials[i].GetColor("_BaseColor") : Color.white);
outlineMat.SetColor("_OutlineColor", outlineColor);
outlineMat.SetFloat("_OutlineThickness", outlineThickness);
_outlineMaterials[i] = outlineMat;
}
}
public void StartHighlight()
{
_renderer.materials = _outlineMaterials;
}
public void StopHighlight()
{
_renderer.materials = _originalMaterials;
}
private void OnDestroy()
{
foreach (Material mat in _outlineMaterials)
{
if (mat != null) Destroy(mat);
}
}
}
🎨 Visual Tuning
_OutlineColor: Adjust to match your desired highlight color and alpha.
_OutlineThickness: Increase slightly (e.g., 1.02–1.05) to control outline width.
Cull Mode: Cull Front in the outline pass ensures only the silhouette is rendered.
✅ Result
Only the outer silhouette glows, no interior edges.
Glow shows through walls and occluders.
Works with multiple materials/submeshes.
No post-processing or complex render features needed.
⚠️ Limitations
Stencil buffer usage: If other effects also use the stencil buffer, conflicts may occur.
Performance: Adds two draw calls per object, so avoid applying to many objects at once.
Perspective distortion: At extreme angles, the outline may appear slightly stretched.
🧪 Example Use Cases
Highlighting interactable objects behind walls.
Showing hidden enemies in stealth games.
Indicating selected units in strategy games.
With this stencil-based silhouette approach, you get a clean, outer-edge glow that behaves exactly like a traditional "highlight through walls" effect — no messy interior edges or full-mesh coverage. 🌟
_OutlineThickness: Start at 1.02, increase slightly for thicker outlines.
_OutlineColor: Use a bright color with some transparency (e.g., new Color(1, 0.5f, 0, 0.3f)).
Offset -1, -1: Helps avoid Z-fighting between base mesh and outline.
ZTest Greater: Ensures outline only draws behind the object’s own geometry.
Cull Front: Ensures only the silhouette (not inner parts) is drawn.
🧪 Updated Script (Handles Multiple Materials)
csharp
using UnityEngine;
public class SilhouetteHighlight : MonoBehaviour
{
private Renderer _renderer;
private Material[] _originalMaterials;
private Material[] _outlineMaterials;
[SerializeField] private Color outlineColor = new Color(1, 0.5f, 0, 0.5f);
[SerializeField] private float outlineThickness = 1.02f;
void Awake()
{
_renderer = GetComponent<Renderer>();
_originalMaterials = _renderer.materials;
_outlineMaterials = new Material[_originalMaterials.Length];
for (int i = 0; i < _originalMaterials.Length; i++)
{
Material outlineMat = new Material(Shader.Find("Custom/SilhouetteOutlineShader"));
outlineMat.SetColor("_BaseColor", _originalMaterials[i].HasProperty("_BaseColor") ? _originalMaterials[i].GetColor("_BaseColor") : Color.white);
outlineMat.SetColor("_OutlineColor", outlineColor);
outlineMat.SetFloat("_OutlineThickness", outlineThickness);
_outlineMaterials[i] = outlineMat;
}
}
public void StartHighlight()
{
_renderer.materials = _outlineMaterials;
}
public void StopHighlight()
{
_renderer.materials = _originalMaterials;
}
private void OnDestroy()
{
foreach (Material mat in _outlineMaterials)
{
if (mat != null) Destroy(mat);
}
}
}
✅ Result
Only the outer silhouette of the object glows — no internal edges or full coverage.
The glow is occluded by the object itself — it won’t show through the front/back of the object.
The glow still shows through walls and occluders.
Works seamlessly with URP and Unity 2022.
No post-processing or complex render features needed.
⚠️ Limitations
Depth Buffer Accuracy: Works best with opaque objects. Transparent or complex meshes may show artifacts.
Performance: Two draw calls per object — avoid applying to many objects simultaneously.
Perspective Distortion: At extreme angles, the outline may appear slightly stretched.
🧪 Example Use Cases
Highlighting interactable objects behind walls.
Showing hidden enemies in stealth games.
Indicating selected units in strategy games.
With this updated approach, you get a clean, outer-edge glow that behaves exactly like a traditional "highlight through walls" effect — no messy interior edges or full-mesh coverage. The glow is occluded by the object itself but visible through the rest of the world. 🌟
Clean outer-edge glow that occludes itself but shows through walls.
No internal edges or full-mesh coverage.
Works seamlessly with URP and Unity 2022.
No post-processing or advanced render features needed.
🧪 Example Use Cases
Highlighting interactable objects behind walls.
Showing hidden enemies in stealth games.
Indicating selected units in strategy games.
With these adjustments, your glow effect becomes a clean, self-occluding outline that behaves naturally in complex scenes. 🌟
}
Shader "Custom/SilhouetteGlow"
{
Properties
{
_OutlineWidth ("Outline Width", Range(0.001, 0.05)) = 0.015
_OutlineColor ("Outline Color", Color) = (1,1,1,1)
_OccludedAlpha ("Occluded Alpha", Range(0, 1)) = 0.3
}
SubShader
{
Tags { "RenderType"="Transparent" "Queue"="Transparent" "RenderPipeline"="UniversalPipeline" }
// --------------------------
// Pass 1: Base Object (Writes to Depth Buffer)
// --------------------------
Pass
{
Name "Base"
Tags { "LightMode"="SRPDefaultUnlit" }
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
struct Attributes
{
float4 positionOS : POSITION;
};
struct Varyings
{
float4 positionHCS : SV_POSITION;
};
Varyings vert(Attributes input)
{
Varyings output;
output.positionHCS = TransformObjectToHClip(input.positionOS);
return output;
}
half4 frag() : SV_Target
{
return half4(1,1,1,1); // Only used for depth
}
ENDHLSL
}
// --------------------------
// Pass 2: Outline (Only visible on silhouette)
// --------------------------
Pass
{
Name "SilhouetteOutline"
Tags { "LightMode"="SRPDefaultUnlit" }
Cull Front
ZWrite Off
ZTest Less // 👈 Only draw if outline is in front of base object
Blend SrcAlpha OneMinusSrcAlpha
Offset -1, -1 // 👈 Push slightly behind to reduce Z-fighting
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
struct Attributes
{
float4 positionOS : POSITION;
float3 normalOS : NORMAL;
};
struct Varyings
{
float4 positionHCS : SV_POSITION;
float3 normalWS : TEXCOORD0;
float3 viewDirWS : TEXCOORD1;
};
CBUFFER_START(UnityPerMaterial)
float4 _OutlineColor;
float _OutlineWidth;
float _OccludedAlpha;
CBUFFER_END
Varyings vert(Attributes input)
{
Varyings output;
VertexNormalInputs normalInputs = GetVertexNormalInputs(input.normalOS);
VertexPositionInputs positionInputs = GetVertexPositionInputs(input.positionOS.xyz);
// Scale the object uniformly outward
float3 expandedPositionWS = positionInputs.positionWS + normalInputs.normalWS * _OutlineWidth;
output.positionHCS = TransformWorldToHClip(expandedPositionWS);
output.normalWS = normalInputs.normalWS;
output.viewDirWS = GetWorldSpaceViewDir(positionInputs.positionWS);
return output;
}
half4 frag(Varyings input) : SV_Target
{
// Fade based on viewing angle (hide front-facing surfaces)
float3 normalWS = normalize(input.normalWS);
float3 viewDirWS = normalize(input.viewDirWS);
float viewDot = abs(dot(normalWS, viewDirWS));
// Only show edges that are perpendicular to view
float edgeFactor = 1.0 - smoothstep(0.4, 0.8, viewDot);
// Apply dynamic alpha
half4 color = _OutlineColor;
color.a *= _OccludedAlpha * edgeFactor;
return color;
}
ENDHLSL
}
}
}
🎨 Visual Tuning Guide
Property
Suggested Value
Purpose
_OutlineWidth
0.01–0.03
Controls thickness of the outline. Smaller = thinner.
_OutlineColor
Color(1,0.5,0,1)
Bright, semi-transparent glow.
_OccludedAlpha
0.2–0.5
Fades the outline where it overlaps the object itself.
🧪 Script for Multiple Materials
csharp
using UnityEngine;
public class SilhouetteHighlight : MonoBehaviour
{
private Renderer _renderer;
private Material[] _originalMaterials;
private Material[] _outlineMaterials;
[SerializeField] private Color outlineColor = new Color(1, 0.5f, 0, 1);
[SerializeField] private float outlineWidth = 0.015f;
[SerializeField] private float occludedAlpha = 0.3f;
void Awake()
{
_renderer = GetComponent<Renderer>();
_originalMaterials = _renderer.materials;
_outlineMaterials = new Material[_originalMaterials.Length];
for (int i = 0; i < _originalMaterials.Length; i++)
{
Material outlineMat = new Material(Shader.Find("Custom/SilhouetteGlow"));
outlineMat.SetColor("_OutlineColor", outlineColor);
outlineMat.SetFloat("_OutlineWidth", outlineWidth);
outlineMat.SetFloat("_OccludedAlpha", occludedAlpha);
_outlineMaterials[i] = outlineMat;
}
}
public void StartHighlight()
{
_renderer.materials = _outlineMaterials;
}
public void StopHighlight()
{
_renderer.materials = _originalMaterials;
}
private void OnDestroy()
{
foreach (Material mat in _outlineMaterials)
{
if (mat != null) Destroy(mat);
}
}
}
🧠 Why This Works
Fix
Purpose
ZTest Less
Ensures outline only draws in front of the base object (self-occlusion)
Cull Front
Renders only back-facing geometry, ensuring only the silhouette appears
Offset -1, -1
Helps avoid Z-fighting between base mesh and outline
edgeFactor
Fades front-facing surfaces to reduce internal edge visibility
OutlineWidth
Adjusted to a smaller value for cleaner, thinner outlines
✅ Result
Clean outer-edge glow that occludes itself but shows through walls.
No internal edges or full-mesh coverage.
Works seamlessly with URP and Unity 2022.
No post-processing or advanced render features needed.
🧪 Example Use Cases
Highlighting interactable objects behind walls.
Showing hidden enemies in stealth games.
Indicating selected units in strategy games.
With this final version, you get a clean, self-occluding outline that behaves naturally in complex scenes — no messy interior edges or thickness issues. 🌟