How to Create a Day and Night Cycle in Unity
October 22, 20242 min read

How to Create a Day and Night Cycle in Unity

Unity 3DGaming Tips
share this article on

Hey game developers! Today, we’re creating a quick and simple day/night cycle in Unity. This feature can add immersion and atmosphere to your games. Let’s dive in!

Here I have a demo scene from Unity’s URP 3D sample. You can use any scene from your own game and add a directional light to represent the sun.

Oasis scene

I will open another scene named Oasis from the same package. This scene has a beautiful sun light and a landscape that we can use. Now, create an empty GameObject and name it “DayNightController”.

Day night controller

We will also create a folder for our scripts.

Day night controller script

Create a new mono behavior script and name it “DayNightController” and attach it to the DayNightController GameObject. Open the script file in your editor. I am using Visual Studio here.

Day night controller script

First, we need to have a reference to our sun light. Lets declare a serialized field and name it sun. We need to declare a float variable named dayDuration. This sets the length of a full day cycle in seconds. Here, it’s set to 60 seconds by default. You can adjust it to your needs. We also declare two color variables, one for day and one for night. You can change this to any color you want.

Day night controller script

Finally timeofday. This represents the current time of day as a value between 0 and 1. 0.25 is used as the starting value to begin the cycle at dawn. 0.5 means noon. 0.75 means evening.

Day night controller script

In the Update method, we increment the timeOfDay based on deltaTime and dayDuration. We are using Time.deltaTime for smooth movement. Next, we need to set timeOfDay to 0 for continuous cycle incase it reaches 1. Now we rotate the light based on the time of day. timeOfDay * 360f converts the 0 to 1 range to 0-360 degrees and subtract 90 to start the light at the horizon at dawn and y to 170 for some tilt. To change the sun light color, we can use Color.lerp for linear interpolation function for color and Mathf.PingPong for creating a blending and smooth back and forth transition between the colors.

Day night controller script

Thats all about the code. Now lets see the result. First, we assign the light to our script field and hit play.

Day night assign light

Now the light is moving over the time and we can see the shadows moving along the light. Lets just move around and see. We can also inspect the light object and observe the color is gradually changing to night.

You can adjust the settings to get better result. That’s all for this article. Lets meet in another. Thank you.


Back to Articles