# 1. Time of Day Clock and Profiles Part of [[Day-Night Cycle and Weather]]. Next: [[2. Sun Moon Ambient and Probe Lighting]]. > [!warning] Code not compiled > Written against the Unity 6000.5 Scripting API (`Gradient.Evaluate`, `AnimationCurve.Evaluate`, `Mathf.Repeat`, `CreateAssetMenu`), not compiled. ## 1.1 One number drives everything Represent time as **`t01`**, the fraction of the day: `0` = midnight, `0.25` = 06:00, `0.5` = noon, `0.75` = 18:00. Every visual parameter is a **curve or gradient over `t01`**. Designers then shape dawn and dusk by editing keys, not code. | Parameter | Type | Typical shape | |---|---|---| | Sun intensity (lux-like or 0-2) | `AnimationCurve` | 0 until 05:30, ramps to 1.2 by 08:00, flat, falls to 0 at 18:30 | | Sun colour | `Gradient` | deep orange at dawn/dusk, near white at noon | | Sun colour temperature (K) | `AnimationCurve` | 2000 K at horizon, 6500 K at noon | | Moon intensity | `AnimationCurve` | inverse of sun, peak ~0.25 | | Ambient sky/equator/ground | 3 x `Gradient` | blue day, purple dusk, dark blue night | | Fog colour / density | `Gradient` / `AnimationCurve` | denser at dawn | | Skybox blend (0 day, 1 night) | `AnimationCurve` | steep around 06:00 and 19:00 | | Star intensity | `AnimationCurve` | 0 by day, 1 at night | | Reflection intensity | `AnimationCurve` | 1 by day, 0.3 at night | > [!tip] Curves beat lerps > A single `Lerp(day, night, x)` gives a long, muddy grey dusk. Curves let you make dusk short and saturated, which is what players remember (see the Level Up! lens in the hub). ## 1.2 `DayNightProfile` ```csharp using UnityEngine; namespace DayNight { /// <summary> /// All time-of-day visuals as curves and gradients keyed on t01 (0 = midnight, 0.5 = noon). /// Type Object: swap profiles per biome or per season. NOT compiled in Unity. /// </summary> [CreateAssetMenu(menuName = "Day Night/Day Night Profile", fileName = "DayNightProfile")] public sealed class DayNightProfile : ScriptableObject { [Header("Clock")] [Tooltip("Real minutes for one full in-game day.")] [Min(0.1f)] public float dayLengthMinutes = 24f; [Tooltip("Hours at which each phase starts (0-24).")] public float dawnStartHour = 5f; public float dayStartHour = 7.5f; public float duskStartHour = 18f; public float nightStartHour = 20f; [Header("Sun")] public AnimationCurve sunIntensity = AnimationCurve.EaseInOut(0f, 0f, 1f, 0f); public Gradient sunColor = new(); [Tooltip("Kelvin. Only used when the light uses colour temperature.")] public AnimationCurve sunTemperature = AnimationCurve.Constant(0f, 1f, 6500f); [Tooltip("Compass heading of the sun's arc in degrees (0 = rises in the east, sets in the west).")] public float sunAzimuth = 0f; [Tooltip("Tilt of the sun's arc. 0 = passes straight overhead.")] [Range(-60f, 60f)] public float sunTilt = 25f; [Header("Moon")] public AnimationCurve moonIntensity = AnimationCurve.Constant(0f, 1f, 0.2f); public Gradient moonColor = new(); [Header("Ambient and fog")] public Gradient ambientSky = new(); public Gradient ambientEquator = new(); public Gradient ambientGround = new(); public Gradient fogColor = new(); public AnimationCurve fogDensity = AnimationCurve.Constant(0f, 1f, 0.005f); public AnimationCurve reflectionIntensity = AnimationCurve.Constant(0f, 1f, 1f); [Header("Sky")] [Tooltip("0 = day cubemap, 1 = night cubemap.")] public AnimationCurve skyNightBlend = AnimationCurve.Constant(0f, 1f, 0f); public AnimationCurve starIntensity = AnimationCurve.Constant(0f, 1f, 0f); public Gradient horizonColor = new(); /// <summary>Hour (0-24) to t01.</summary> public static float HourToT01(float hour) => Mathf.Repeat(hour, 24f) / 24f; public DayPhase PhaseAt(float hour) { hour = Mathf.Repeat(hour, 24f); if (hour >= nightStartHour || hour < dawnStartHour) return DayPhase.Night; if (hour < dayStartHour) return DayPhase.Dawn; if (hour < duskStartHour) return DayPhase.Day; return DayPhase.Dusk; } void OnValidate() { // Keep phases in order so PhaseAt stays meaningful. dawnStartHour = Mathf.Clamp(dawnStartHour, 0f, 24f); dayStartHour = Mathf.Clamp(dayStartHour, dawnStartHour, 24f); duskStartHour = Mathf.Clamp(duskStartHour, dayStartHour, 24f); nightStartHour = Mathf.Clamp(nightStartHour, duskStartHour, 24f); } } public enum DayPhase { Night, Dawn, Day, Dusk } } ``` **Authoring the asset:** *Create > Day Night > Day Night Profile*. Edit curves with time on 0..1 (0.25 = 06:00). Gradients use the same axis: put colour keys at 0.21 (05:00), 0.27 (06:30), 0.5, 0.75, 0.83. Make two profiles (e.g. *Temperate* and *Desert*) to prove the Type Object idea. ## 1.3 `TimeOfDayClock` ```csharp using System; using UnityEngine; namespace DayNight { /// <summary> /// Advances in-game time. Uses scaled Time.deltaTime, so Time.timeScale = 0 pauses the day too. /// Publishes state; never touches lights itself. NOT compiled in Unity. /// </summary> [DefaultExecutionOrder(-50)] public sealed class TimeOfDayClock : MonoBehaviour { public static TimeOfDayClock Instance { get; private set; } [SerializeField] DayNightProfile profile; [SerializeField, Range(0f, 24f)] float startHour = 8f; [SerializeField] bool running = true; [Tooltip("Extra multiplier for debugging (e.g. 60 = an hour per second at 24-min days).")] [SerializeField, Min(0f)] float debugSpeed = 1f; float _hour; int _day; int _lastWholeHour = -1; DayPhase _phase; public DayNightProfile Profile => profile; /// <summary>Hour of day, 0 (inclusive) to 24 (exclusive).</summary> public float Hour => _hour; /// <summary>Fraction of the day, 0 = midnight, 0.5 = noon.</summary> public float T01 => _hour / 24f; public int Day => _day; public DayPhase Phase => _phase; public bool IsNight => _phase == DayPhase.Night; public bool Running { get => running; set => running = value; } /// <summary>In-game hours that pass per real second at speed 1.</summary> public float HoursPerSecond => 24f / (profile.dayLengthMinutes * 60f); public event Action<float> Ticked; // t01, every frame the clock moves public event Action<int> HourChanged; // whole hour 0-23 public event Action<DayPhase, DayPhase> PhaseChanged; // from, to public event Action<int> DayChanged; // new day index void Awake() { if (Instance != null && Instance != this) { Debug.LogWarning("Two TimeOfDayClocks in the scene; disabling the second.", this); enabled = false; return; } Instance = this; _hour = Mathf.Repeat(startHour, 24f); _phase = profile.PhaseAt(_hour); _lastWholeHour = Mathf.FloorToInt(_hour); } void OnDestroy() { if (Instance == this) Instance = null; } void Start() => Publish(force: true); void Update() { if (!running) return; Advance(Time.deltaTime * HoursPerSecond * debugSpeed); } /// <summary>Move time forward by a number of in-game hours (sleeping, waiting, cutscenes).</summary> public void Skip(float hours) { if (hours <= 0f) return; // Step in whole hours so HourChanged and PhaseChanged fire for every boundary crossed. while (hours > 1f) { Advance(1f); hours -= 1f; } Advance(hours); } /// <summary>Jump straight to an hour today (or tomorrow if it is earlier than now), firing events.</summary> public void SkipTo(float targetHour) { float delta = Mathf.Repeat(targetHour - _hour, 24f); Skip(delta); } /// <summary>Set time without firing hour events for skipped hours (loading a save).</summary> public void SetTime(int day, float hour) { _day = Mathf.Max(0, day); _hour = Mathf.Repeat(hour, 24f); _lastWholeHour = Mathf.FloorToInt(_hour); _phase = profile.PhaseAt(_hour); Publish(force: true); } void Advance(float hours) { _hour += hours; while (_hour >= 24f) { _hour -= 24f; _day++; DayChanged?.Invoke(_day); } Publish(force: false); } void Publish(bool force) { int whole = Mathf.FloorToInt(_hour); if (force || whole != _lastWholeHour) { _lastWholeHour = whole; HourChanged?.Invoke(whole); } DayPhase p = profile.PhaseAt(_hour); if (force || p != _phase) { DayPhase from = _phase; _phase = p; PhaseChanged?.Invoke(from, p); } Ticked?.Invoke(T01); } public string Clock24 => quot;{Mathf.FloorToInt(_hour):00}:{Mathf.FloorToInt(_hour % 1f * 60f):00}"; #if UNITY_EDITOR void OnValidate() { // Scrub startHour in the Inspector during Play Mode to preview lighting. if (Application.isPlaying && profile != null && Instance == this) SetTime(_day, startHour); } #endif } } ``` ### Why these choices - **Scaled delta time.** The pause menu sets `Time.timeScale = 0` (see [[4. Pause Menu Time Scale and Audio]]); the day stops with it. If you want the sky to keep moving under a pause menu, use `Time.unscaledDeltaTime` instead. That is a design decision, so make it consciously. - **`Skip` steps hour by hour.** Sleeping from 22:00 to 06:00 must still fire `HourChanged(23, 0, 1 ... 6)` so shops open, lamps switch off and crops grow. Loading a save uses `SetTime` instead, because replaying eight hours of events on load would double-apply them. - **`[DefaultExecutionOrder(-50)]`.** The clock moves before drivers read it in the same frame. - **One `Instance`.** Runtime-spawned NPCs find the clock through it. Scene components should still use an Inspector reference (testable, explicit). ## 1.4 Debug overlay (optional) ```csharp using UnityEngine; namespace DayNight { /// <summary>Tiny IMGUI readout for development builds. NOT compiled in Unity.</summary> public sealed class TimeOfDayDebug : MonoBehaviour { [SerializeField] TimeOfDayClock clock; void OnGUI() { if (!Debug.isDebugBuild || clock == null) return; GUILayout.BeginArea(new Rect(10, 10, 220, 120), GUI.skin.box); GUILayout.Label(quot;Day {clock.Day} {clock.Clock24} {clock.Phase}"); if (GUILayout.Button("+1 hour")) clock.Skip(1f); if (GUILayout.Button("Skip to 19:00")) clock.SkipTo(19f); clock.Running = GUILayout.Toggle(clock.Running, "Running"); GUILayout.EndArea(); } } } ``` ## 1.5 Steps 1. Create folder `Assets/DayNight/` with an assembly definition `DayNight.Runtime` (it will reference `Unity.RenderPipelines.Core.Runtime` and `Unity.VisualEffectGraph.Runtime` in later parts). 2. Create a `DayNightProfile`, set `dayLengthMinutes = 24` while tuning (one real minute = one game hour). 3. Add an empty `Environment` GameObject with `TimeOfDayClock` and `TimeOfDayDebug`. 4. Press Play; click *+1 hour* and watch the readout and the Console (temporarily `Debug.Log` from a `HourChanged` subscriber). ## Sources - `AnimationCurve.Evaluate`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/AnimationCurve.Evaluate.html - `Gradient.Evaluate`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Gradient.Evaluate.html - `Mathf.Repeat`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Mathf.Repeat.html - `Time.deltaTime` / `Time.timeScale`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Time.html - [[ScriptableObject Architecture]], [[Game Programming Patterns (Review)]] (Game Loop, Observer, Type Object)