Creating a Day and Night Cycle in Unity – Unity By Example

Creating a Day and Night Cycle in Unity

Unity 3D provides a multitude of options for creating interactive game environments, including the ability to simulate a day and night cycle. This effect can enhance the realism and atmosphere of the game, evoking different emotional responses from players. There are several techniques for implementing the day and night cycle in Unity 3D, such as using lighting, textures, and animations.

Steps

  • Create script TimeProgressor.cs
using UnityEngine;

public class TimeProgressor : MonoBehaviour
{
    [Header("Time Params")]
    [SerializeField, Range(0, 24)] private float _timeOfDay; 
    [SerializeField] private float _orbitSpeed;
    [SerializeField] private float _axisOffset;
    [SerializeField] private Gradient _nightLight;
    [SerializeField] private AnimationCurve _sunCurve;

    [Header("Objects")]
    [SerializeField] private Light _sun;

    [Header("Time")]
    private int _hour;
    private int _minute;

    private void OnValidate()
    {
        ProgressTime();
    }

    private void Update()
    {
        _timeOfDay += Time.deltaTime * _orbitSpeed; 
        ProgressTime();
    }

    private void ProgressTime()
    {

        float currentTime = _timeOfDay / 24; 
        float sunRotation = Mathf.Lerp(-90, 270, currentTime);

        _sun.transform.rotation = Quaternion.Euler(sunRotation, _axisOffset, 0);

        _hour = Mathf.FloorToInt(_timeOfDay);
        _minute = Mathf.FloorToInt((_timeOfDay / (24f / 1440f) % 60)); 

        RenderSettings.ambientLight = _nightLight.Evaluate(currentTime);
        _sun.intensity = _sunCurve.Evaluate(currentTime); 

        _timeOfDay %= 24;
    }
}

  • Add the TimeProgressor.cs script to an empty object

In conclusion, the day and night cycle effect in Unity 3D is a powerful tool for game developers to create immersive and engaging gameplay experiences. By utilizing the available techniques, developers can craft dynamic environments that offer players a unique and compelling journey through the game world.

Download

4 3 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments