# 5. Day-Night and Weather Gameplay Hooks
Part of [[Day-Night Cycle and Weather]]. Prev: [[4. Weather States with Rain and Snow VFX]]. Next: [[6. Worked Example Village Day Night Storm]].
> [!warning] Code not compiled
> Written against the Unity 6000.5 Scripting API (`UnityEvent`, `MaterialPropertyBlock`, `NavMeshAgent`, `NavMesh.SamplePosition`, `JsonUtility`, `File.Replace`/`File.Move`). Not compiled.
If night is only darker, players wait it out. These hooks make time and weather **change the rules**: lamps create light pools, NPCs go home, guards hear less in the rain, fires go out.
## 5.1 `HourRange` and `TimeOfDayEvent`
```csharp
using System;
using UnityEngine;
using UnityEngine.Events;
namespace DayNight
{
/// <summary>A span of hours that may wrap past midnight (e.g. 19 to 6).</summary>
[Serializable]
public struct HourRange
{
[Range(0f, 24f)] public float from;
[Range(0f, 24f)] public float to;
public HourRange(float from, float to) { this.from = from; this.to = to; }
public bool Contains(float hour)
{
hour = Mathf.Repeat(hour, 24f);
return from <= to ? hour >= from && hour < to : hour >= from || hour < to;
}
}
/// <summary>
/// Designer hook: UnityEvents when the clock enters and leaves an hour range.
/// Evaluated on HourChanged (whole hours) and once on Start, so loading mid-range works.
/// NOT compiled in Unity.
/// </summary>
public sealed class TimeOfDayEvent : MonoBehaviour
{
[SerializeField] TimeOfDayClock clock;
[SerializeField] HourRange activeHours = new(19f, 6f);
public UnityEvent onEnter;
public UnityEvent onExit;
bool? _inside;
void OnEnable()
{
if (!clock) clock = TimeOfDayClock.Instance;
if (clock) clock.HourChanged += OnHour;
}
void OnDisable()
{
if (clock) clock.HourChanged -= OnHour;
}
void Start()
{
if (clock) OnHour(Mathf.FloorToInt(clock.Hour));
}
void OnHour(int hour)
{
bool inside = activeHours.Contains(hour + 0.001f);
if (_inside == inside) return;
_inside = inside;
(inside ? onEnter : onExit)?.Invoke();
}
}
}
```
Whole-hour resolution is deliberate: it is cheap, and `TimeOfDayClock.Skip` fires every hour it crosses (part 1), so sleeping through the night still switches everything.
## 5.2 `TimedLamp`
```csharp
using UnityEngine;
namespace DayNight
{
/// <summary>
/// Street lamp / window: light and emission on during activeHours (and optionally in heavy cloud).
/// Toggles Light.enabled (not the GameObject) so StealthTarget keeps the light in its list.
/// NOT compiled in Unity.
/// </summary>
public sealed class TimedLamp : MonoBehaviour
{
[SerializeField] TimeOfDayClock clock;
[SerializeField] HourRange activeHours = new(19f, 6.5f);
[SerializeField] Light[] lights;
[SerializeField] Renderer[] emissiveRenderers;
[SerializeField, ColorUsage(false, true)] Color emissionOn = new(4f, 3f, 1.6f);
[Tooltip("Random delay so a whole street does not switch in the same frame (in-game minutes).")]
[SerializeField] Vector2 randomDelayMinutes = new(0f, 20f);
[SerializeField, Range(0f, 1f)] float alsoOnWhenCloudAbove = 0.9f;
[Tooltip("Optional: a StealthZone or other object enabled only while lit.")]
[SerializeField] GameObject litOnlyObject;
static readonly int EmissionId = Shader.PropertyToID("_EmissionColor");
MaterialPropertyBlock _mpb;
float _offsetHours;
bool? _on;
void Awake()
{
_mpb = new MaterialPropertyBlock();
_offsetHours = Random.Range(randomDelayMinutes.x, randomDelayMinutes.y) / 60f;
if (!clock) clock = TimeOfDayClock.Instance;
}
void Update()
{
if (!clock) return;
bool on = activeHours.Contains(clock.Hour - _offsetHours);
WeatherController w = WeatherController.Instance;
if (w && w.State.cloudCover >= alsoOnWhenCloudAbove) on = true;
if (_on == on) return; // dirty flag
_on = on;
foreach (Light l in lights) if (l) l.enabled = on;
foreach (Renderer r in emissiveRenderers)
{
if (!r) continue;
r.GetPropertyBlock(_mpb);
_mpb.SetColor(EmissionId, on ? emissionOn : Color.black);
r.SetPropertyBlock(_mpb);
}
if (litOnlyObject) litOnlyObject.SetActive(on);
}
}
}
```
- The lamp material must have **Emission** enabled (URP Lit keyword) for `_EmissionColor` to show; a black emission colour then reads as "off".
- Lamps are **realtime** lights here. If they are baked, bake them into the `Night` lighting scenario instead (part 2.5) and keep only the emissive toggle.
- Count lamps: URP has a per-object additional-light limit (Forward) or uses Forward+ clustering. Many lamps are a reason to use Forward+ ([[1.Realtime Mixed and Baked Lights]]).
## 5.3 `ScheduledActivity`: NPC daily routines
```csharp
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
namespace DayNight
{
/// <summary>
/// Daily routine: go to the target of whichever entry contains the current hour.
/// Re-evaluated on each whole hour; loading mid-day teleports to the right place.
/// NOT compiled in Unity.
/// </summary>
[RequireComponent(typeof(NavMeshAgent))]
public sealed class ScheduledActivity : MonoBehaviour
{
[Serializable]
public struct Entry
{
public string activity; // "Sleep", "Work", "Tavern" - for animation or barks
public HourRange hours;
public Transform place;
}
[SerializeField] List<Entry> schedule = new();
[SerializeField] Transform fallbackPlace;
[SerializeField] bool snapOnStart = true;
NavMeshAgent _agent;
TimeOfDayClock _clock;
public string CurrentActivity { get; private set; }
public event Action<string> ActivityChanged;
void Awake() => _agent = GetComponent<NavMeshAgent>();
void OnEnable()
{
_clock = TimeOfDayClock.Instance;
if (_clock) _clock.HourChanged += OnHour;
}
void OnDisable()
{
if (_clock) _clock.HourChanged -= OnHour;
}
void Start()
{
if (!_clock) return;
Entry e = Pick(_clock.Hour);
if (snapOnStart && e.place && NavMesh.SamplePosition(e.place.position, out NavMeshHit hit, 2f, NavMesh.AllAreas))
_agent.Warp(hit.position);
Go(e);
}
void OnHour(int hour) => Go(Pick(hour + 0.001f));
Entry Pick(float hour)
{
foreach (Entry e in schedule)
if (e.hours.Contains(hour)) return e;
return new Entry { activity = "Idle", place = fallbackPlace };
}
void Go(Entry e)
{
if (e.activity != CurrentActivity)
{
CurrentActivity = e.activity;
ActivityChanged?.Invoke(e.activity);
}
if (!e.place || !_agent.isOnNavMesh) return;
if (NavMesh.SamplePosition(e.place.position, out NavMeshHit hit, 2f, NavMesh.AllAreas))
_agent.SetDestination(hit.position);
}
}
}
```
NavMesh details (areas, `SamplePosition`, off-mesh links for doors) are in [[NavMesh in Unity 6 (AI Navigation 2.x)]]. For many NPCs, stagger them: give each entry's `place` several spots, or add a few minutes of random offset as in `TimedLamp`.
## 5.4 Stealth: night and rain
[[Organic Enemy Sensing]]'s `StealthTarget` already handles **night** for free: it adds `0.5 * intensity` for every enabled directional light that is not blocked. The moon is dim and `SunMoonController` disables the sun at night, so visibility drops automatically; lamps (`TimedLamp`) create the light pools that the [[Stealth Game Capstone]] builds its levels around.
**Rain** needs one small, documented addition to `EnemySenses` (two lines):
```csharp
// In EnemySenses (Organic Enemy Sensing), add:
public static float EnvironmentSightScale = 1f; // fog, heavy rain
public static float EnvironmentHearingScale = 1f; // rain noise masks footsteps
// In Look(), after computing gain:
// float gain = sightGainPerSecond * ... * perceptionScale * EnvironmentSightScale;
// In OnNoise(), when computing loudness:
// float loud = noise.Loudness * hearingMultiplier * perceptionScale * EnvironmentHearingScale;
```
Then a bridge sets them from the weather:
```csharp
using UnityEngine;
namespace DayNight
{
/// <summary>
/// Weather -> stealth. Rain masks noise and shortens effective sight; fog shortens sight.
/// Requires the two static fields added to EnemySenses. NOT compiled in Unity.
/// </summary>
public sealed class WeatherStealthBridge : MonoBehaviour
{
[SerializeField] WeatherController weather;
[Tooltip("Rain rate at which the full effect applies.")]
[SerializeField] float heavyRainRate = 15000f;
[SerializeField, Range(0f, 1f)] float hearingInHeavyRain = 0.5f;
[SerializeField, Range(0f, 1f)] float sightInHeavyRain = 0.75f;
[SerializeField] float fogDensityForMinSight = 0.03f;
[SerializeField, Range(0f, 1f)] float sightInThickFog = 0.5f;
void OnEnable() => weather.StateUpdated += Apply;
void OnDisable()
{
weather.StateUpdated -= Apply;
EnemySenses.EnvironmentSightScale = 1f;
EnemySenses.EnvironmentHearingScale = 1f;
}
void Apply(WeatherState s)
{
float rain = Mathf.Clamp01(s.rainRate / heavyRainRate);
float fog = Mathf.Clamp01(s.extraFog / fogDensityForMinSight);
EnemySenses.EnvironmentHearingScale = Mathf.Lerp(1f, hearingInHeavyRain, rain);
EnemySenses.EnvironmentSightScale =
Mathf.Lerp(1f, sightInHeavyRain, rain) * Mathf.Lerp(1f, sightInThickFog, fog);
}
}
}
```
> [!note] Assemblies
> `WeatherStealthBridge` references `EnemySenses`. If `DayNight.Runtime` is its own assembly definition, either add a reference to the assembly that contains the sensing code or put this bridge in your game assembly. The environment code itself should not depend on stealth.
**Telegraph it.** Players only use a rule they can see. Show it in the HUD (a rain icon next to the visibility meter) or in a guard bark ("Can't hear a thing in this rain"). Level Up! fairness applies: a hidden modifier feels like a bug.
## 5.5 `RainExposure`: things that react to rain outdoors
```csharp
using UnityEngine;
using UnityEngine.Events;
namespace DayNight
{
/// <summary>
/// Fires events when rain starts or stops falling on this object (sky visible above it).
/// Use for campfires going out, puddles, crops being watered. NOT compiled in Unity.
/// </summary>
public sealed class RainExposure : MonoBehaviour
{
[SerializeField] float minRainRate = 1000f;
[SerializeField] LayerMask roofMask = ~0;
[SerializeField] float checkInterval = 1f;
public UnityEvent onRainStart;
public UnityEvent onRainStop;
public bool IsExposed { get; private set; }
float _next;
void Update()
{
if (Time.time < _next) return;
_next = Time.time + checkInterval;
WeatherController w = WeatherController.Instance;
bool raining = w && w.State.rainRate >= minRainRate;
bool underRoof = Physics.Raycast(transform.position + Vector3.up * 0.2f, Vector3.up, 100f,
roofMask, QueryTriggerInteraction.Ignore);
bool exposed = raining && !underRoof;
if (exposed == IsExposed) return;
IsExposed = exposed;
(exposed ? onRainStart : onRainStop)?.Invoke();
}
}
}
```
Example: on a campfire from the [[Crafting System]] worked example, wire `onRainStart` to the fire's *Extinguish* method; a crafted *Tarp* placed above it blocks the raycast and keeps it lit. That turns weather into a reason to craft.
Other cheap hooks:
| Hook | How |
|---|---|
| Snow slows the player | multiply move speed by `Mathf.Lerp(1, 0.75, state.snowCover)` in the controller ([[Character Controllers]]) |
| Wind pushes thrown objects | `rb.AddForce(state.wind * windFactor, ForceMode.Acceleration)` on projectiles in flight |
| Shops open 08-18 | `TimeOfDayEvent` toggling the shop's interactable |
| Night-only creatures | spawner enabled by `TimeOfDayEvent` |
| Quest "meet at the well at midnight" | quest condition reading `TimeOfDayClock.Instance.Hour` ([[Quest Systems]]) |
## 5.6 `EnvironmentSave`
```csharp
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
namespace DayNight
{
/// <summary>
/// Saves day, hour and weather (by profile name) as JSON, written atomically.
/// Load uses SetTime/Restore, which do not replay skipped hour events. NOT compiled in Unity.
/// </summary>
public sealed class EnvironmentSave : MonoBehaviour
{
[Serializable]
struct Data
{
public int day;
public float hour;
public string weather;
public float weatherHoursLeft;
public float wetness;
public float snowCover;
}
[SerializeField] TimeOfDayClock clock;
[SerializeField] WeatherController weather;
[Tooltip("Every WeatherProfile that can be saved; looked up by asset name.")]
[SerializeField] List<WeatherProfile> knownProfiles = new();
[SerializeField] string fileName = "environment.json";
string PathOnDisk => Path.Combine(Application.persistentDataPath, fileName);
public void Save()
{
var d = new Data
{
day = clock.Day,
hour = clock.Hour,
weather = weather.Current ? weather.Current.name : "",
weatherHoursLeft = weather.HoursLeft,
wetness = weather.State.wetness,
snowCover = weather.State.snowCover,
};
string tmp = PathOnDisk + ".tmp";
File.WriteAllText(tmp, JsonUtility.ToJson(d, true));
if (File.Exists(PathOnDisk)) File.Replace(tmp, PathOnDisk, null);
else File.Move(tmp, PathOnDisk);
}
public bool Load()
{
if (!File.Exists(PathOnDisk)) return false;
try
{
Data d = JsonUtility.FromJson<Data>(File.ReadAllText(PathOnDisk));
clock.SetTime(d.day, d.hour);
WeatherProfile p = knownProfiles.Find(x => x && x.name == d.weather);
if (p) weather.Restore(p, d.wetness, d.snowCover, d.weatherHoursLeft);
return true;
}
catch (Exception e)
{
Debug.LogWarning(
quot;Environment save unreadable, using defaults: {e.Message}");
return false;
}
}
}
}
```
Saving by **asset name** is simple but breaks if you rename a profile; add a stable `id` string to `WeatherProfile` if saves must survive refactors (the same advice as item ids in [[Inventory Systems]]). For a full save system, fold `Data` into your existing save file ([[3. Player Data Save and Load]]).
## Sources
- `UnityEvent`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Events.UnityEvent.html
- `MaterialPropertyBlock`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/MaterialPropertyBlock.html
- `NavMeshAgent.Warp` / `SetDestination`, `NavMesh.SamplePosition`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/AI.NavMesh.SamplePosition.html
- `JsonUtility`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/JsonUtility.html
- `Application.persistentDataPath`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Application-persistentDataPath.html
- [[Organic Enemy Sensing]], [[Stealth Game Capstone]], [[NavMesh in Unity 6 (AI Navigation 2.x)]], [[Level Up! (Review)]]