Creating a Day and Night cycle in Unity

Making a Day and Night cycle in Unity is pretty simple. You just need to rotate the directional light in the scene. In this tutorial, we will see

  1. How to add directional light to your scene.
  2. How to rotate the directional light.
  3. Set the Day night cycle time.

To add a directional light, Click add on the hierarchy window >Light>Directional light.

Let’s add a Simple plane and a cube just for the sake of this tutorial.

Set the x rotation of the direction light to zero. You need not worry about the Y and Z axis.

Unity Black Friday Deals

Your scene should look similar to a sunset or sunrise.

You can change the x rotation to 90 and see that it’s like noon and if you change the rotation to 180 it will look like sunset.

Now your day cycle is from 0 to 180 and night cycle is from 180 to 360(or -180). You need to write a code to increase the x rotation of your directional light based on your requirement. Here is a sample code. I have added a point light to the scene so that the cube is visible when it’s totally dark.

using UnityEngine;

public class day_night : MonoBehaviour
{
    Vector3 rot=Vector3.zero;
    float day_cycle=20;

    // Update is called once per frame
    void Update()
    {
        rot.x=day_cycle*Time.deltaTime;
        transform.Rotate(rot,Space.World);
        
    }
}

The day_cylcle is the degree per second value. You can decide on your day cycle time and change the value accordingly.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.