# 3. Blended Skybox Shader for URP
Part of [[Day-Night Cycle and Weather]]. Prev: [[2. Sun Moon Ambient and Probe Lighting]]. Next: [[4. Weather States with Rain and Snow VFX]].
> [!warning] Code not compiled
> The shader and the C# have not been compiled. The shader uses URP `Core.hlsl` and SRP Core `EntityLighting.hlsl` (`DecodeHDREnvironment`); both include paths were checked against the Unity Graphics repository on 2026-11-21.
## 3.1 Why not Shader Graph?
The obvious route, an Unlit Shader Graph assigned as the skybox material, is **not supported in URP**. Unity closed the bug report as "As Designed" (issue 20676, Sources). Procedural skies in URP therefore use a hand-written shader with the skybox tags:
- `"Queue"="Background"`, `"RenderType"="Background"`, `"PreviewType"="Skybox"`
- `Cull Off`, `ZWrite Off`
Unity draws the skybox with a mesh centred on the camera, so the **object-space vertex position is the view direction**. That is all the shader needs.
## 3.2 The shader
Create `Assets/DayNight/Shaders/BlendedSkybox.shader`:
```hlsl
Shader "DayNight/Blended Skybox"
{
Properties
{
[NoScaleOffset] _DayCube ("Day Cubemap (HDR)", Cube) = "grey" {}
_DayTint ("Day Tint", Color) = (1, 1, 1, 1)
[NoScaleOffset] _NightCube ("Night Cubemap (stars, HDR)", Cube) = "black" {}
_NightTint ("Night Tint", Color) = (1, 1, 1, 1)
_Blend ("Night Blend", Range(0, 1)) = 0
_StarRotation ("Star Rotation (degrees)", Float) = 0
_StarIntensity ("Star Intensity", Range(0, 4)) = 1
_HorizonColor ("Horizon Color", Color) = (1, 0.6, 0.4, 1)
_HorizonHeight ("Horizon Height", Range(0.01, 1)) = 0.15
_HorizonStrength ("Horizon Strength", Range(0, 1)) = 0.5
_Cloudiness ("Overcast", Range(0, 1)) = 0
_CloudColor ("Overcast Color", Color) = (0.5, 0.55, 0.6, 1)
_SunDir ("Direction To Sun", Vector) = (0, 1, 0, 0)
_SunColor ("Sun Color", Color) = (1, 0.95, 0.85, 1)
_SunSize ("Sun Size", Range(0.0005, 0.05)) = 0.004
_SunGlow ("Sun Glow", Range(0, 4)) = 1
_MoonDir ("Direction To Moon", Vector) = (0, -1, 0, 0)
_MoonColor ("Moon Color", Color) = (0.7, 0.8, 1, 1)
_MoonSize ("Moon Size", Range(0.0005, 0.05)) = 0.003
_Exposure ("Exposure", Range(0, 8)) = 1
}
SubShader
{
Tags
{
"Queue" = "Background"
"RenderType" = "Background"
"PreviewType" = "Skybox"
"RenderPipeline" = "UniversalPipeline"
}
Cull Off
ZWrite Off
Pass
{
Name "BlendedSkybox"
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_instancing
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/EntityLighting.hlsl"
TEXTURECUBE(_DayCube); SAMPLER(sampler_DayCube);
TEXTURECUBE(_NightCube); SAMPLER(sampler_NightCube);
CBUFFER_START(UnityPerMaterial)
float4 _DayCube_HDR;
float4 _NightCube_HDR;
half4 _DayTint;
half4 _NightTint;
half _Blend;
float _StarRotation;
half _StarIntensity;
half4 _HorizonColor;
half _HorizonHeight;
half _HorizonStrength;
half _Cloudiness;
half4 _CloudColor;
float4 _SunDir;
half4 _SunColor;
float _SunSize;
half _SunGlow;
float4 _MoonDir;
half4 _MoonColor;
float _MoonSize;
half _Exposure;
CBUFFER_END
struct Attributes
{
float4 positionOS : POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct Varyings
{
float4 positionCS : SV_POSITION;
float3 viewDir : TEXCOORD0;
UNITY_VERTEX_OUTPUT_STEREO
};
float3 RotateAroundY(float3 d, float degrees)
{
float s, c;
sincos(radians(degrees), s, c);
return float3(c * d.x - s * d.z, d.y, s * d.x + c * d.z);
}
// 1 inside the disc, soft edge, 0 outside. size = 1 - cos(angular radius), roughly radius^2 / 2.
half Disc(float3 dir, float3 toBody, float size)
{
float d = dot(dir, normalize(toBody));
return smoothstep(1.0 - size, 1.0 - size * 0.7, d);
}
Varyings vert(Attributes input)
{
Varyings output;
UNITY_SETUP_INSTANCE_ID(input);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
output.positionCS = TransformObjectToHClip(input.positionOS.xyz);
output.viewDir = input.positionOS.xyz;
return output;
}
half4 frag(Varyings input) : SV_Target
{
float3 dir = normalize(input.viewDir);
half3 day = DecodeHDREnvironment(
SAMPLE_TEXTURECUBE_LOD(_DayCube, sampler_DayCube, dir, 0), _DayCube_HDR) * _DayTint.rgb;
float3 starDir = RotateAroundY(dir, _StarRotation);
half3 night = DecodeHDREnvironment(
SAMPLE_TEXTURECUBE_LOD(_NightCube, sampler_NightCube, starDir, 0), _NightCube_HDR)
* _NightTint.rgb * _StarIntensity;
half3 col = lerp(day, night, _Blend);
// Overcast: replace the sky with a flat cloud colour that also darkens at night.
half3 overcast = _CloudColor.rgb * lerp(1.0h, 0.08h, _Blend);
col = lerp(col, overcast, _Cloudiness);
// Horizon band (sunrise/sunset glow, haze). Fog colour should match this.
half h = 1.0h - saturate(abs(dir.y) / _HorizonHeight);
col = lerp(col, _HorizonColor.rgb, h * h * _HorizonStrength);
// Hide bodies below the horizon.
half aboveHorizon = smoothstep(-0.01, 0.02, dir.y);
half clearSky = 1.0h - _Cloudiness * 0.9h;
float sunDot = saturate(dot(dir, normalize(_SunDir.xyz)));
half sun = Disc(dir, _SunDir.xyz, _SunSize) + pow(sunDot, 256.0) * _SunGlow;
col += _SunColor.rgb * sun * aboveHorizon * clearSky;
half moon = Disc(dir, _MoonDir.xyz, _MoonSize);
col += _MoonColor.rgb * moon * aboveHorizon * clearSky;
return half4(col * _Exposure, 1.0h);
}
ENDHLSL
}
}
Fallback Off
}
```
Notes on the shader:
- **HDR decode.** Unity provides `<texture>_HDR` decode values for cubemaps; `DecodeHDREnvironment` handles RGBM/dLDR encodings and is a pass-through for float formats.
- **Stars rotate, the day sky does not.** Rotating the night cubemap around Y with time makes the night feel alive and costs one rotation.
- **Overcast** is a cheap stand-in for clouds. For real clouds, add a third cubemap or a scrolling 2D noise layer; the structure stays the same.
- **VR / stereo.** The instancing and stereo macros are there so the shader does not break under single-pass instanced rendering. This tutorial was not tested in XR.
## 3.3 Material and cubemaps
1. Import a daytime HDRI (`.exr` or `.hdr`). Texture Inspector: **Texture Shape: Cube**, Mapping *Auto*, HDR format (BC6H on desktop). Repeat with a night sky (stars, milky way).
2. Create a material from `DayNight/Blended Skybox`; assign both cubemaps.
3. Lighting window > Environment > **Skybox Material**: the new material.
4. Leave **Environment Lighting Source** on **Gradient** (part 2). The skybox is visual only; ambient comes from `AmbientDriver`.
## 3.4 `SkyboxDriver`
```csharp
using UnityEngine;
namespace DayNight
{
/// <summary>
/// Feeds the blended skybox from the clock, the profile and the sun/moon rig.
/// Works on a material instance so the asset on disk is never modified in Play Mode.
/// NOT compiled in Unity.
/// </summary>
public sealed class SkyboxDriver : MonoBehaviour
{
[SerializeField] TimeOfDayClock clock;
[SerializeField] SunMoonController sunMoon;
[SerializeField] Light sun;
[SerializeField] Light moon;
[SerializeField] Material skyboxTemplate;
[Tooltip("Full star rotations per in-game day.")]
[SerializeField] float starTurnsPerDay = 1f;
/// <summary>0..1, set by weather (part 4).</summary>
public float Cloudiness { get; set; }
static readonly int BlendId = Shader.PropertyToID("_Blend");
static readonly int StarRotationId = Shader.PropertyToID("_StarRotation");
static readonly int StarIntensityId = Shader.PropertyToID("_StarIntensity");
static readonly int HorizonColorId = Shader.PropertyToID("_HorizonColor");
static readonly int SunDirId = Shader.PropertyToID("_SunDir");
static readonly int SunColorId = Shader.PropertyToID("_SunColor");
static readonly int MoonDirId = Shader.PropertyToID("_MoonDir");
static readonly int CloudinessId = Shader.PropertyToID("_Cloudiness");
Material _instance;
Material _original;
void OnEnable()
{
_original = RenderSettings.skybox;
_instance = new Material(skyboxTemplate) { name = skyboxTemplate.name + " (Runtime)" };
RenderSettings.skybox = _instance;
if (clock) clock.Ticked += Apply;
}
void OnDisable()
{
if (clock) clock.Ticked -= Apply;
RenderSettings.skybox = _original;
if (_instance) Destroy(_instance);
}
void Apply(float t01)
{
DayNightProfile p = clock.Profile;
_instance.SetFloat(BlendId, p.skyNightBlend.Evaluate(t01));
_instance.SetFloat(StarIntensityId, p.starIntensity.Evaluate(t01));
_instance.SetFloat(StarRotationId, (clock.Day + t01) * 360f * starTurnsPerDay);
_instance.SetColor(HorizonColorId, p.horizonColor.Evaluate(t01));
_instance.SetVector(SunDirId, -sun.transform.forward);
_instance.SetColor(SunColorId, p.sunColor.Evaluate(t01));
_instance.SetVector(MoonDirId, -moon.transform.forward);
_instance.SetFloat(CloudinessId, Cloudiness);
}
}
}
```
**Execution order.** `SunMoonController` and `SkyboxDriver` both subscribe to `Ticked`. The sun direction read here is whatever the sun had when this handler runs. If the sky disc lags one frame behind the shadows, compute the direction from the clock instead of reading the light, or subscribe the driver after the sun controller (enable order).
## 3.5 Reflections that follow the sky
Environment reflections are generated from the skybox, but changing the skybox material at runtime does not regenerate them by itself. Options, cheapest first:
1. **Realtime reflection probes** (part 2.6): one large probe covering the outdoor area captures the current sky. Re-render it on phase changes and every 30 game minutes.
2. **`RenderSettings.reflectionIntensity`** from the profile (part 2.3): dims baked noon reflections at night. Cheap but not accurate.
3. **Skybox as ambient source + `DynamicGI.UpdateEnvironment`**: the docs describe it as scheduling an asynchronous readback of the environment cubemap; requests made faster than the readback completes are silently ignored. `AmbientDriver` rate-limits it.
## 3.6 Check yourself
- At 06:00 the sun disc sits on the horizon in the same direction as the shadows point away from.
- At 22:00 stars are visible, rotating slowly; the day cubemap is gone.
- Overcast 1: no sun disc, sky flat grey, stars hidden.
## Sources
- Unity issue 20676 (Shader Graph Unlit not supported as a URP skybox, "As Designed"): https://issuetracker.unity.com/issues/20676
- URP `Core.hlsl` and SRP Core `EntityLighting.hlsl` (`DecodeHDREnvironment`): https://github.com/Unity-Technologies/Graphics/tree/master/Packages/com.unity.render-pipelines.core/ShaderLibrary
- `RenderSettings.skybox`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/RenderSettings-skybox.html
- `Shader.PropertyToID`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Shader.PropertyToID.html
- `DynamicGI.UpdateEnvironment`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/DynamicGI.UpdateEnvironment.html
- [[URP Shaders and Shader Graph]], [[5.Reflection Probes and Environment Lighting]]