簡體   English   中英

我怎樣才能讓“時間”不斷更新

[英]How I can make "Time" to be update constantly

我是統一的初學者游戲開發者,我“獨自”開始新的小項目,在我的游戲中我遇到了一個小問題。

我的問題是時間,即游戲中的時鍾不同步,不同步,我有些懷疑。

我知道我可能又做錯了一步,也許我在整個函數中放了一個錯誤的等式,什么都不起作用了,但更簡單地說,我想制作一個游戲界面是桌面和時鍾的游戲我在下面對其進行了編碼,它無法隨時間更新,我等待並嘗試了我應用的許多解決方案但它們沒有用,所以我將代碼留在下面

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

public class DateTime : MonoBehaviour
{

    public Text timeLockScreenText;
    public Text dateLockScreenText;
    public Text timeTaskBarText;
    string time = System.DateTime.UtcNow.ToLocalTime().ToString("HH:mm");
    string date = System.DateTime.UtcNow.ToLocalTime().ToString("MM-dd-yyyy");

    // Update is called once per frame
    void Update()
    {
        InvokeRepeating("DateTimeV",0f,1f);
    }

    public void DateTimeV()
    {
    timeLockScreenText.text = time;
    dateLockScreenText.text = date;
    timeTaskBarText.text = timeLockScreenText.text;
    }
}

現在我有一些理論:

  • 一個是在游戲中,就像在現實生活中一樣,就像任何個人計算機用戶一樣,當我們打開它時,會有一個帶有時鍾的鎖屏,我們一直按回車進入以訪問互聯網和桌面上的其他文件,所以我的理論是鎖屏是一個游戲對象,就像桌面的可見性一樣,即如果鎖屏處於活動狀態,桌面是不可見的,反之亦然,時鍾不會更新,因為假設我們在桌面上鎖屏被禁用,這就是腳本不起作用的原因,您必須制作兩個單獨的腳本,一個用於鎖屏,一個用於桌面,實際上是用於桌面上的時鍾
  • 或者我不知道如何寫好代碼

我嘗試在 InvokeRepeting 中放入 Update() 函數,StartCourutine 和 IEnumerator 函數,但我沒有解決方案

我對 Unity 一無所知,但似乎您在最初分配timedate后永遠不會更新它們的值。 也許像這樣的事情可以解決問題,您只需在方法中分配正確的值:

public void DateTimeV()
{
    DateTime utcNow = System.DateTime.UtcNow.ToLocalTime();

    timeLockScreenText.text = utcNow.ToString("HH:mm");
    dateLockScreenText.text = utcNow.ToString("MM-dd-yyyy");
    timeTaskBarText.text = timeLockScreenText.text;
}

使用固定更新,以及來自Rufus L的代碼:

void FixedUpdate() => DateTimeV();

public void DateTimeV()
{
    DateTime utcNow = System.DateTime.UtcNow.ToLocalTime();

    timeLockScreenText.text = utcNow.ToString("HH:mm");
    dateLockScreenText.text = utcNow.ToString("MM-dd-yyyy");
    timeTaskBarText.text = timeLockScreenText.text;
}

Rufus L所說的 + 你只會使用InvokeRepeating一次,例如

private void Start()
{
    InvokeRepeating(nameof(DateTimeV), 0f, 1f);
}

或者使用一個簡單的計數器

private float timer;

private void Update ()
{
    timer += Time.deltaTime;

    if(timer > 1f)
    {
        timer -= 1f;

        DateTimeV();
    }
}

或協程

private IEnumerator Start()
{
    while(true)
    {
        DateTimeV();

        yield return new WaitForSeconds(1f);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM