# 2. Sun Moon Ambient and Probe Lighting
Part of [[Day-Night Cycle and Weather]]. Prev: [[1. Time of Day Clock and Profiles]]. Next: [[3. Blended Skybox Shader for URP]].
> [!warning] Code not compiled
> Written against the Unity 6000.5 Scripting API (`Light`, `RenderSettings`, `DynamicGI`, `ReflectionProbe`) and SRP Core 17.5 (`ProbeReferenceVolume`). Not compiled.
## 2.1 Lighting setup that survives a moving sun
| Setting | Value | Why |
|---|---|---|
| Sun and moon lights | Directional, **Mode: Realtime** | baked or mixed direct light cannot move; see [[1.Realtime Mixed and Baked Lights]] |
| Lamps, interior lights | Mixed or Baked (or Realtime if they switch often) | captured per lighting scenario (2.5) or left realtime |
| Lighting window > Environment > Environment Lighting > Source | **Gradient** | driven from script (2.3); cheap, and it updates APV sky occlusion without `DynamicGI.UpdateEnvironment` |
| Lighting window > Sun Source | empty (script sets `RenderSettings.sun`) | |
| Global Illumination | APV (Light Probe System: Adaptive Probe Volumes in the URP asset) | see [[4.Light Probes and Adaptive Probe Volumes]] |
| Lightmapper | Progressive **GPU** | required for APV sky occlusion |
> [!note] Gradient vs Trilight
> The Lighting window calls the three-colour ambient mode **Gradient**; the API enum value is `AmbientMode.Trilight`. They are the same thing.
## 2.2 `SunMoonController`
The sun travels an arc set by `t01`: rotation X = `t01 * 360 - 90`, so at 06:00 the sun is on the eastern horizon, at noon it points straight down (before tilt), at 18:00 it is on the western horizon. The moon is the opposite direction.
```csharp
using UnityEngine;
using UnityEngine.Rendering;
namespace DayNight
{
/// <summary>
/// Rotates and colours the sun and moon directional lights from the DayNightProfile.
/// Only the light that is above the horizon is enabled, casts shadows and is RenderSettings.sun.
/// NOT compiled in Unity.
/// </summary>
public sealed class SunMoonController : MonoBehaviour
{
[SerializeField] TimeOfDayClock clock;
[SerializeField] Light sun;
[SerializeField] Light moon;
[Tooltip("Below this sun elevation (degrees) the moon takes over.")]
[SerializeField] float handoverElevation = -2f;
[SerializeField] bool useColorTemperature = true;
/// <summary>0 = clear, 1 = overcast. Set by weather (part 4).</summary>
public float CloudCover { get; set; }
[SerializeField, Range(0f, 1f)] float overcastSunMultiplier = 0.25f;
public float SunElevation { get; private set; }
public Light ActiveLight { get; private set; }
void OnEnable()
{
if (clock) clock.Ticked += Apply;
if (useColorTemperature && !GraphicsSettings.lightsUseLinearIntensity)
Debug.LogWarning("Colour temperature needs GraphicsSettings.lightsUseLinearIntensity = true.", this);
}
void OnDisable()
{
if (clock) clock.Ticked -= Apply;
}
public void Apply(float t01)
{
DayNightProfile p = clock.Profile;
Quaternion arc = Quaternion.Euler(0f, p.sunAzimuth, 0f)
* Quaternion.AngleAxis(p.sunTilt, Vector3.forward)
* Quaternion.Euler(t01 * 360f - 90f, 0f, 0f);
sun.transform.rotation = arc;
Vector3 sunForward = sun.transform.forward;
moon.transform.rotation = Quaternion.LookRotation(-sunForward, Vector3.up);
// Light points down when the sun is up, so elevation = asin(-forward.y).
SunElevation = Mathf.Asin(Mathf.Clamp(-sunForward.y, -1f, 1f)) * Mathf.Rad2Deg;
float cloud = Mathf.Lerp(1f, overcastSunMultiplier, CloudCover);
sun.intensity = Mathf.Max(0f, p.sunIntensity.Evaluate(t01)) * cloud;
sun.color = p.sunColor.Evaluate(t01);
moon.intensity = Mathf.Max(0f, p.moonIntensity.Evaluate(t01)) * Mathf.Lerp(1f, 0.5f, CloudCover);
moon.color = p.moonColor.Evaluate(t01);
if (useColorTemperature)
{
sun.useColorTemperature = true;
sun.colorTemperature = p.sunTemperature.Evaluate(t01);
}
bool sunUp = SunElevation > handoverElevation;
SetActive(sunUp ? sun : moon, sunUp ? moon : sun);
}
void SetActive(Light on, Light off)
{
if (ActiveLight == on) return; // dirty flag: only touch state on handover
ActiveLight = on;
on.enabled = true;
on.shadows = LightShadows.Soft;
off.shadows = LightShadows.None;
off.enabled = false;
RenderSettings.sun = on;
}
}
}
```
**Steps**
1. Rename the scene's Directional Light to `Sun`; Mode Realtime, Shadow Type Soft.
2. Duplicate it as `Moon`; colour pale blue, intensity 0.2.
3. Add `SunMoonController` to `Environment`; assign clock, sun, moon.
4. In the profile, shape `sunIntensity` and `moonIntensity` so **both are near zero at the handover** (around 06:00 and 18:30). Then the switch is invisible.
5. Scrub `startHour` in Play Mode: shadows should swing, lengthen at dusk and switch to the moon.
> [!tip] One shadow-casting directional light
> URP's main-light shadow map comes from one directional light (the main light). Swapping which light casts them at the horizon (when both are dim) avoids paying for two directional shadow maps and avoids double shadows. Check what URP picked as the main light in the Frame Debugger.
## 2.3 `AmbientDriver`
```csharp
using UnityEngine;
using UnityEngine.Rendering;
namespace DayNight
{
/// <summary>
/// Drives Gradient (Trilight) ambient, fog and reflection intensity from the profile.
/// Optional throttled DynamicGI.UpdateEnvironment when the ambient source is the skybox.
/// NOT compiled in Unity.
/// </summary>
public sealed class AmbientDriver : MonoBehaviour
{
[SerializeField] TimeOfDayClock clock;
[SerializeField] bool driveFog = true;
[SerializeField] FogMode fogMode = FogMode.ExponentialSquared;
[Header("Only if ambient source = Skybox")]
[Tooltip("Minimum real seconds between DynamicGI.UpdateEnvironment calls (expensive).")]
[SerializeField, Min(0.5f)] float environmentUpdateInterval = 5f;
[SerializeField, Range(0.001f, 0.2f)] float environmentUpdateThreshold = 0.03f;
/// <summary>Set by weather: 0..1 darkening of ambient, extra fog density.</summary>
public float WeatherDim { get; set; }
public float WeatherFogBoost { get; set; }
public Color WeatherFogTint { get; set; } = Color.grey;
float _lastEnvUpdateTime = -999f;
float _lastEnvT01 = -1f;
void OnEnable()
{
if (clock) clock.Ticked += Apply;
}
void OnDisable()
{
if (clock) clock.Ticked -= Apply;
}
public void Apply(float t01)
{
DayNightProfile p = clock.Profile;
float dim = Mathf.Lerp(1f, 0.55f, WeatherDim);
if (RenderSettings.ambientMode == AmbientMode.Trilight)
{
RenderSettings.ambientSkyColor = p.ambientSky.Evaluate(t01) * dim;
RenderSettings.ambientEquatorColor = p.ambientEquator.Evaluate(t01) * dim;
RenderSettings.ambientGroundColor = p.ambientGround.Evaluate(t01) * dim;
}
else if (RenderSettings.ambientMode == AmbientMode.Skybox)
{
ThrottledEnvironmentUpdate(t01);
}
RenderSettings.reflectionIntensity = p.reflectionIntensity.Evaluate(t01) * dim;
if (driveFog)
{
RenderSettings.fog = true;
RenderSettings.fogMode = fogMode;
Color fog = p.fogColor.Evaluate(t01);
RenderSettings.fogColor = Color.Lerp(fog, WeatherFogTint * fog.maxColorComponent, WeatherDim);
RenderSettings.fogDensity = p.fogDensity.Evaluate(t01) + WeatherFogBoost;
}
}
void ThrottledEnvironmentUpdate(float t01)
{
// Dirty flag + rate limit: UpdateEnvironment schedules a GPU readback and is costly.
bool changedEnough = Mathf.Abs(Mathf.DeltaAngle(_lastEnvT01 * 360f, t01 * 360f)) / 360f
> environmentUpdateThreshold;
if (!changedEnough) return;
if (Time.realtimeSinceStartup - _lastEnvUpdateTime < environmentUpdateInterval) return;
_lastEnvT01 = t01;
_lastEnvUpdateTime = Time.realtimeSinceStartup;
DynamicGI.UpdateEnvironment();
}
}
}
```
**Steps**
1. Lighting window > Environment: Source **Gradient**. The driver only writes the three colours when the mode is Trilight, so the Skybox path is opt-in.
2. In the profile, make the ground colour darker than the equator and the night sky a **readable** blue, not black. A good floor is about 10-15% of the noon brightness.
3. Fog: exponential squared with density 0.002-0.01 for outdoor scenes. Fog colour should match the horizon colour of the skybox (part 3), or distant objects will look like cut-outs.
## 2.4 APV sky occlusion: ambient that respects roofs
Plain ambient lights the inside of a hut as brightly as the field outside. **APV sky occlusion** bakes, per probe, how much of the sky each probe can see; at runtime the current sky colour is multiplied by that visibility. Interiors stay dark at noon and stay dark at night. A full day/night cycle is exactly what it was designed for.
From the 6000.5 manual (Sources):
1. Use the **Progressive GPU** lightmapper.
2. Lighting window > **Adaptive Probe Volumes** panel: enable **Sky Occlusion**; optionally **Sky Direction** for more accurate directional sky light.
3. Bake.
4. At runtime, keep Environment Source on **Gradient** or **Color** and change `RenderSettings.ambientSkyColor` (and the other two colours). This is what `AmbientDriver` does. With Source **Skybox**, you must call `DynamicGI.UpdateEnvironment`, which the manual warns has a large performance cost.
Indirect light from the **sun** is not part of sky occlusion; it is whatever is baked into the probes (or nothing, if the sun is excluded from the bake). For a moving sun that is fine: the direct light is realtime and dominates.
## 2.5 Lighting scenarios: lamps on at night
Sky occlusion handles the sky. **Lighting Scenarios** handle baked lights that change: street lamps that turn on at night, an interior that is lit only after dark. Each scenario is a separate bake of the same probe layout; at runtime APV can switch or **blend** between two scenarios.
**Enable and bake (6000.5 manual)**
1. URP Asset > Lighting > Light Probe Lighting: enable **Lighting Scenarios**, and **Scenario Blending** if you want smooth transitions.
2. Lighting window > Adaptive Probe Volumes > Lighting Scenarios: add `Day`, `Dusk`, `Night`.
3. For each scenario: make it active, set lights to match (e.g. lamps enabled and baked only for `Night`), bake.
4. Do not move probes or geometry between bakes; the scenarios must share the probe layout.
**Runtime blending**
```csharp
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
namespace DayNight
{
/// <summary>
/// Blends APV lighting scenarios by hour, e.g. Night(20) -> Dawn(5) -> Day(8) -> Dusk(18) -> Night.
/// Requires Lighting Scenarios and Scenario Blending in the URP asset. NOT compiled in Unity.
/// </summary>
public sealed class ApvScenarioBlender : MonoBehaviour
{
[Serializable]
public struct ScenarioKey
{
[Range(0f, 24f)] public float hour;
public string scenario;
}
[SerializeField] TimeOfDayClock clock;
[Tooltip("Sorted by hour. Each key is fully applied at its hour and blends toward the next.")]
[SerializeField] List<ScenarioKey> keys = new();
[SerializeField, Min(1)] int cellsBlendedPerFrame = 4;
[SerializeField, Range(0.001f, 0.1f)] float minFactorStep = 0.01f;
string _from;
string _to;
float _lastFactor = -1f;
void OnEnable()
{
if (clock) clock.Ticked += Apply;
keys.Sort((a, b) => a.hour.CompareTo(b.hour));
}
void OnDisable()
{
if (clock) clock.Ticked -= Apply;
}
void Apply(float t01)
{
if (keys.Count < 2) return;
ProbeReferenceVolume prv = ProbeReferenceVolume.instance;
if (prv == null || !prv.isInitialized) return;
prv.numberOfCellsBlendedPerFrame = cellsBlendedPerFrame;
float hour = t01 * 24f;
int i = keys.Count - 1;
for (int k = 0; k < keys.Count; k++)
if (keys[k].hour <= hour) i = k;
ScenarioKey a = keys[i];
ScenarioKey b = keys[(i + 1) % keys.Count];
float span = Mathf.Repeat(b.hour - a.hour, 24f);
float into = Mathf.Repeat(hour - a.hour, 24f);
float factor = span > 0f ? Mathf.Clamp01(into / span) : 0f;
if (_from != a.scenario)
{
// Switch the active scenario only when the segment changes, then re-issue the blend.
prv.lightingScenario = a.scenario;
_from = a.scenario;
_to = null;
_lastFactor = -1f;
}
if (_to != b.scenario || Mathf.Abs(factor - _lastFactor) >= minFactorStep)
{
prv.BlendLightingScenario(b.scenario, factor);
_to = b.scenario;
_lastFactor = factor;
}
}
}
}
```
> [!note] Keys hold, then blend
> With keys `Night 20, Day 7, Dusk 18`, the blend runs over the whole span between keys. If you want long stable plateaus, add duplicate keys: `Day 8` and `Day 17` hold `Day` from 08:00 to 17:00 because blending `Day` to `Day` is a no-op.
**Sky occlusion or scenarios?** Use sky occlusion for the continuous sky change (always). Add scenarios only when **baked local lights** change with the time of day. If all lamps are realtime, you do not need scenarios.
## 2.6 `ReflectionProbeScheduler`
Baked reflection probes captured at noon make night scenes glow. Use **realtime** probes, refreshed *Via Scripting*, and re-render them rarely and one at a time.
```csharp
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
namespace DayNight
{
/// <summary>
/// Re-renders realtime reflection probes every N in-game minutes, one probe per frame.
/// Probes: Type Realtime, Refresh Mode Via Scripting. NOT compiled in Unity.
/// </summary>
public sealed class ReflectionProbeScheduler : MonoBehaviour
{
[SerializeField] TimeOfDayClock clock;
[SerializeField] List<ReflectionProbe> probes = new();
[SerializeField, Min(1f)] float everyGameMinutes = 30f;
float _lastHour = -999f;
int _next = -1; // -1 = idle
void Start()
{
foreach (ReflectionProbe p in probes)
{
p.mode = ReflectionProbeMode.Realtime;
p.refreshMode = ReflectionProbeRefreshMode.ViaScripting;
}
if (clock) clock.PhaseChanged += (_, _) => RequestRefresh();
RequestRefresh();
}
/// <summary>Call after big changes (phase change, weather change, lightning).</summary>
public void RequestRefresh() => _next = 0;
void Update()
{
if (clock != null)
{
float hours = clock.Day * 24f + clock.Hour;
if (hours - _lastHour >= everyGameMinutes / 60f)
{
_lastHour = hours;
RequestRefresh();
}
}
if (_next < 0 || _next >= probes.Count) { _next = -1; return; }
if (probes[_next] != null && probes[_next].isActiveAndEnabled)
probes[_next].RenderProbe();
_next++;
}
}
}
```
`RenderProbe()` renders all six faces in one call. If that frame spike is too big, use fewer probes, a lower probe resolution, or switch a probe to *Every Frame* with **time slicing** (*Individual Faces* or *All Faces At Once*); the scripting docs say time slicing applies to the *Every Frame* refresh mode.
## 2.7 Check yourself
- Scrub through 24 hours: is there a moment where the scene goes **black**? Raise the ambient floor or moon intensity.
- Walk into a building at noon: with sky occlusion it should be darker inside than outside.
- Watch the Profiler (*Rendering*, *GI*) while time runs: no `UpdateEnvironment` spikes if Source is Gradient.
## Sources
- `Light.colorTemperature`, `Light.useColorTemperature`, `GraphicsSettings.lightsUseLinearIntensity`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Light-colorTemperature.html
- `RenderSettings` (ambientMode, ambient colours, fog, reflectionIntensity, sun): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/RenderSettings.html
- `Rendering.AmbientMode`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Rendering.AmbientMode.html
- `DynamicGI.UpdateEnvironment`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/DynamicGI.UpdateEnvironment.html
- `ReflectionProbe.RenderProbe`, `ReflectionProbeRefreshMode`, `ReflectionProbeTimeSlicingMode`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/ReflectionProbe.RenderProbe.html
- APV sky occlusion (6000.5): https://docs.unity.com/en-us/engine/6000.5/manual/lighting-overview/lighting/probevolumes/probe-volumes-change-lighting-at-runtime/skyocclusion
- APV lighting scenarios (6000.5): https://docs.unity.com/en-us/engine/6000.5/manual/lighting-overview/lighting/probevolumes/probe-volumes-change-lighting-at-runtime/bakedifferentlightingsetups
- `ProbeReferenceVolume` (SRP Core 17.5: `instance`, `isInitialized`, `lightingScenario`, `BlendLightingScenario`, `numberOfCellsBlendedPerFrame`): https://docs.unity3d.com/Packages/
[email protected]/api/UnityEngine.Rendering.ProbeReferenceVolume.html
- [[Lighting and Baking]], [[5.Reflection Probes and Environment Lighting]]