day/night 循环又跟踪天数?

day/night cycle and also track days?

我正在尝试制作一个日夜循环,同时记录过去了多少天。我看了一个教程开始,为此 post,我删除了所有不必要的东西,比如旋转太阳和改变颜色。

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);
    }
}

我遇到的最大问题是 timeMultiplier 我宁愿有一个 dayLength 变量来表示一天应该持续多长时间,以分钟为单位,所以一天是 10 分钟 int dayLength = 600; 或类似的东西,但我不确定我将如何实现它。

此外,我尝试添加一个方法来检查一天是否已经过去,但代码最终 运行 大约 20 次。

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

试试这个代码

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
    }
}

您也可以删除范围属性以指定比实时日期更慢的日期。