Unity 2D游戏开发:创建游戏时间管理系统(36)

256 阅读1分钟

一、脚本编程

1、创建时间管理器,添加TimeManager.cs

挂载到空物体上

image.png

image.png

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

public class TimeManager : MonoBehaviour
{
    private int gameSecond,gameMinute,gameHour,gameDay,gameMonth,gameYear;

    private Season gameSeason = Season.春天;

    private int monthInSeason = 3;

    public bool gameClockPause;

    public float tikTime;

    private void Awake()
    {
        NewGameTime();
    }
    private void Update()
    {
       if (!gameClockPause)
        {
            tikTime += Time.deltaTime;
            if (tikTime > Settings.secondThreshold)
            {
                tikTime -= Settings.secondThreshold;
                UpdateGameTime();
            }
            
        }
        
    }
    private void NewGameTime()
    {
        gameSecond = 0;
        gameMinute = 0;
        gameHour = 7;
        gameDay = 1;
        gameMonth = 1;
        gameYear = 2022;
        gameSeason = Season.春天;
    }
    private void UpdateGameTime()
    {
        gameSecond++;
        if (gameSecond > Settings.secondHold)
        {
            gameMinute++;
            gameSecond = 0;

            if (gameMinute > Settings.minuteHold)
            { 
                gameHour++;
                gameMinute = 0;
                if (gameHour > Settings.hourHold)
                {
                    gameDay++;
                    gameHour = 0;
                    if (gameDay > Settings.dayHold)
                    { 
                        gameMonth++;
                        gameDay = 1;

                        if (gameMonth > 12)
                            gameMonth = 1;
                        
                        monthInSeason--; 
                        if (monthInSeason == 0)
                        { 
                            monthInSeason = 3;

                            int seasonNumber = (int)gameSeason;
                            seasonNumber++;


                            if (seasonNumber > Settings.seasonHold)
                            {
                                seasonNumber = 0;
                                gameYear++;
                            }

                            gameSeason = (Season)seasonNumber;
                            if (gameYear > 9999)
                            {
                                gameYear = 2022;
                            }
                        }

                    }
                }
            }
        }

       // Debug.Log("Second:" + gameSecond + "Minute" + gameMinute);
    }
}

2、创建季节枚举变量,修改Enum.cs文件

image.png

public enum Season
{ 
    春天,夏天,秋天,冬天
}

3、创建时间变量,修改Setting.cs

    //与时间有关变量
    public const float secondThreshold = 0.012f;//数值越小时间越快

    public const int secondHold = 59;

    public const int minuteHold = 59;

    public const int hourHold = 23;

    public const int dayHold = 30;

    public const int seasonHold = 3;

二、脚本逻辑

未完待续......