Skip to content

Instantly share code, notes, and snippets.

@Vigowebs
Last active August 7, 2024 04:16
Show Gist options
  • Save Vigowebs/16936ca790990ba163ebfc2f30c4af71 to your computer and use it in GitHub Desktop.
Save Vigowebs/16936ca790990ba163ebfc2f30c4af71 to your computer and use it in GitHub Desktop.
Day/Night Cycle in Unity (Quick Version)
using UnityEngine;
public class DayNightController : MonoBehaviour
{
// The main light source reference from the scene
[SerializeField]
private Light sun;
// This sets the length of a full day cycle in seconds. Here, it's set to 60 seconds by default. You can adjust this for you need.
[SerializeField]
private float dayDuration = 60.0f;
// This is the color of the light at day time
[SerializeField]
private Color dayColor = Color.white;
// This is the color of the light at night time
[SerializeField]
private Color nightColor = new Color(0.1f, 0.1f, 0.3f);
// This represents the current time of day as a value between 0 and 1. We split the time of day as four parts (0.25 - dawn, 0.5 - nooon, 0.75 - evening, 1 - night)
// 0.25 is used as the starting value to begin the cycle at dawn.
private float timeOfDay = 0.25f;
void Update()
{
// Increase the timeOfDay
timeOfDay += Time.deltaTime / dayDuration;
// If timeOfDay reaches 1, we need to set it to 0 for continuous cycle of day/night.
if (timeOfDay >= 1f) timeOfDay -= 1f;
// This rotates the sun based on the time of day.
// timeOfDay * 360f converts the 0-1 range to 0-360 degrees. The -90 offset starts the sun at the horizon at dawn.
// 170 on the Y-axis tilts the sun's path to create more realistic lighting angles.
sun.transform.rotation = Quaternion.Euler((timeOfDay * 360f) - 90, 170, 0);
// This sets the color of the directional light representing the sun.
// We use Color.Lerp, linear interpolation function to blend between day and night.
// This is the key to creating a smooth back-and-forth transition.
// Mathf.PingPong creates a value that ping-pongs back and forth between 0 and the second parameter (1 in this case).
// timeOfDay * 2 is used because we want a full cycle (night to day to night) to occur over the course of a single day.
/*
* Here's how it works over time:
* When timeOfDay is 0, PingPong returns 0, so the color is nightColor.
* As timeOfDay increases to 0.25, PingPong approaches 0.5, blending to a middle color.
* At timeOfDay 0.5, PingPong returns 1, so the color is fully dayColor.
* As timeOfDay continues to 0.75, PingPong goes back to 0.5, returning to the middle color.
* When timeOfDay reaches 1, we're back to nightColor.
* This creates a smooth cycle: night → dawn → day → dusk → night, all using a single line of code.
*/
sun.color = Color.Lerp(nightColor, dayColor, Mathf.PingPong(timeOfDay * 2, 1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment