Unity Stardew Valley Day Night Cycle

While working on my current project, I needed a day night cycle similar to Stardew Valley. If you’ve ever played Stardew Valley, you’ll know it tracks hours, minutes, days, seasons, and years. It does this by having a 20 hour day from 6AM – 2AM, after which the character passes out.

I started this journey knowing I’d use a coroutine for my minutes tick. I wanted it to happen every 10 real life seconds and once it reached a value 60 I’d increment my hour and reset my minutes indicator.

        private void IncrementGameTime()
        {
            minutes += 10;
            if (minutes >= 60) {
                minutes = 0;
                hour += 1.0f;
                AdjustDarkness();
            }        
            
            if(hour >= 26)
            {
                hour = 6.0f;
                IncrementDays();
            }
        }

The entire system hinges on the code provided above. The method triggers an increment of days which impacts seasons, which also impacts the number of years that has been played.

I wanted my in-game time to be displayed as standard time as opposed to a 24 hour format, however the data is being represented in a 24 data format. So I had to write these additional methods.

GenerateStandardFormatHour does exactly as it reads, it converts a 24 hour time format to a 12 hour time format, with this I also needed to generate a meridiem value. A meridem is nothing more than the AM (ante meridem) which means before and PM ( post meridem ) meaning after.

        private float GenerateStandardFormatHour()
        {
            float stdHr = 0.0f;
            if (hour >= 13)
                stdHr = hour - 12.0f;
            else
                stdHr = hour;

            return stdHr;
        }

       private string GenerateMeridiem()
        {
            if(hour < 13)
            {
                return "AM";
            } else
            {
                return "PM";
            }
        }

So the script for this functionality is contained within one file, its easy to use. Drop it into a game manager or empty game object in your scene. Reference the script and observe the values. Where you take the functionality after this is up to you, you could increment a darkness overlay or do whatever your game needs. Additional coding will be needed though.

You can get the full script from my github:

https://github.com/Diaonic/UnityDayNightCycle/blob/master/DayNightCycle.cs

Cheers,

Corey