Home > Software design >  day/night cycle and also track days?
day/night cycle and also track days?

Time:05-30

I'm trying to make a day and night cycle that also keeps track of how many days passed. I watched a tutorial to start and for this post, I removed all the unnecessary stuff like rotating the sun and changing colors.

public class TimeController : MonoBehaviour
{
    [SerializeField]
    private float timeMultiplier;

    [SerializeField]
    private float startHour;

    private DateTime currentTime;

    void Start()
    {
        currentTime = DateTime.Now.Date   TimeSpan.FromHours(startHour);
    }

    void Update()
    {
        UpdateTimeOfDay();
    }

    private void UpdateTimeOfDay()
    {
        currentTime = currentTime.AddSeconds(Time.deltaTime * timeMultiplier);
    }
}

The biggest issue I have with this is instead of timeMultiplier I'd rather have like a dayLength variable which represents how long a day should last in minutes so one day is 10minutes int dayLength = 600; or something like that, but I'm not sure how I'd implement that.

Also, I tried adding a method for checking if a day has passed, but the code ended up running like 20 times.

    public int currentDay = 1;
    private void HasDayPassed()
    {
        if (currentTime.Hour == 0)
        {
            Debug.Log("New day");
            currentDay  ;
        }
    }

CodePudding user response:

Try this code

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TimeController : MonoBehaviour
{
    public const float SecondsInDay = 86400f;

    [SerializeField] [Range(0, SecondsInDay)] private float _realtimeDayLength = 60;
    [SerializeField] private float _startHour;

    private DateTime _currentTime;
    private DateTime _lastDayTime;

    private int _currentDay = 1;

    private void Start()
    {
        _currentTime = DateTime.Now   TimeSpan.FromHours(_startHour);
        _lastDayTime = _currentTime;
    }

    private void Update()
    {
        // Calculate a seconds step that we need to add to the current time
        float secondsStep = SecondsInDay / _realtimeDayLength * Time.deltaTime;
        _currentTime = _currentTime.AddSeconds(secondsStep);

        // Check and increment the days passed
        TimeSpan difference = _currentTime - _lastDayTime;
        if(difference.TotalSeconds >= SecondsInDay)
        {
            _lastDayTime = _currentTime;
            _currentDay  ;
        }

        // Next do your animation stuff
        AnimateSun();
    }

    private void AnimateSun()
    {
        // Animate sun however you want
    }
}

Also you can remove the range attribute to specify more slower day than the realtime day.

  • Related