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
- How to add directional light to your scene.
- How to rotate the directional light.
- 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.
Your scene should look similar to a sunset or sunrise.
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.