This is a first attempt and test using the directional light
using UnityEngine;
public class DayNightCycle : MonoBehaviour
{
[Header("Time Settings")] [Range(0, 24)]
public float timeOfDay = 12.0f;
// seconds in real time for a full day cycle
public float dayDuration = 240.0f;
[Header("Sun Settings")] public Light sun;
public Gradient sunColor;
public AnimationCurve sunIntensity;
[Header("Sky Settings")] public Material skyboxMaterial;
public float maxAmbientIntensity = 1.0f;
public Gradient ambientColor;
void Update()
{
// Update time of day
timeOfDay += Time.deltaTime / dayDuration * 24.0f;
if (timeOfDay >= 24.0f) {
timeOfDay -= 24.0f;
}
// Calculate sun rotation
// 15 degrees per hour, offset to start at dawn
var sunRotation = timeOfDay * 15.0f - 90.0f;
// Apply rotation to the sun
sun.transform.rotation = Quaternion.Euler(sunRotation, -30.0f, 0);
// Update light color and intensity based on time of day
var dayNightRatio = Mathf.InverseLerp(0, 24, timeOfDay);
if (timeOfDay > 12) {
dayNightRatio = Mathf.InverseLerp(24, 12, timeOfDay);
}
sun.color = sunColor.Evaluate(dayNightRatio);
sun.intensity = sunIntensity.Evaluate(dayNightRatio);
// Update ambient lighting
RenderSettings.ambientLight = ambientColor.Evaluate(dayNightRatio);
// Update skybox (if using a skybox that supports time of day)
if (skyboxMaterial != null && skyboxMaterial.HasProperty("_Exposure")) {
skyboxMaterial.SetFloat("_Exposure", sunIntensity.Evaluate(dayNightRatio));
}
}
}