Day / Night cycle

I just managed to swing a day to night cycle in Unity and it only took me … 30 minutes! and it’s beautiful to boot.  I’m using some assets from Synty Studios which turned me on to an awesome, and totally free, post processing stack that looks great in the day to night cycle.

  1. Basic Setup

a. Find the SM_Generic_SkyDome in the POLYGON_Renderbox assets. You’ll put this in your scene and it will be hooked up later to the script that manages the transitions.

b. Add a directional light to the scene. It doesn’t really matter what color you use, we’ll set those up later in our script.

c. Run the game and make sure everything looks nifty.

2. New Script

Create a new script named DayNightTransitionManager and attach it to an empty object in the scene.

    public class DayNightTransitionManager : MonoBehaviour {

        public Light light;

        public List<Material> materials;
        public List<Color> colors;
        public float timeBetweenCycles = 60.0f;
        public float transitionTime = 20.0f;

        public MeshRenderer rend;

        private float lastCycle = 0.0f;
        private int pointer = 0;
        private int next = 1;
        private int max = 0;

        private bool inTransition = false;

        void Start() {
            lastCycle = Time.time;
            max = materials.Count;

            rend.material = materials[ 0 ];
            light.color = colors[ 0 ];
        }

        void Update() {

            if ( !inTransition ) {
                if ( Time.time - lastCycle > timeBetweenCycles ) {
                    inTransition = true;
                    lastCycle = Time.time;

                    Debug.Log( "DayNight moving to transition phase" );
                }
            } else {

                float amount = Mathf.Clamp( ( Time.time - lastCycle ) / transitionTime, 0.0f, 1.0f );
                rend.material.Lerp( materials[ pointer ], materials[ next ], amount );
                light.color = Color.Lerp( colors[ pointer ], colors[ next ], amount );

                if ( Time.time - lastCycle > transitionTime ) {
                    inTransition = false;
                    lastCycle = Time.time;

                    rend.material = materials[ next ];
                    light.color = colors[ next ];

                    next = ( next + 1 ) % max;
                    pointer = ( pointer + 1 ) % max;

                    Debug.Log( "DayNight moving out of transition phase" );
                }
            }

        }
    
    }

 

3. Connecting it all up

a. Drag your Directional Light into the Light field in the inspector.

b. Drag the SkyDome object into the Rend field in the inspector.

c. I set the materials and colors sizes to 4, and added the following elements to materials:

Skydome_Day
Skydome_Sunset
Skydome_Night
Skydome_EarlyMorning

d. I used the following colors for each stage:

#FFF4D6FF
#FCC88500
#35388000
#FA240000

4. Enjoy!