[英]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 一無所知,但似乎您在最初分配time
和date
后永遠不會更新它們的值。 也許像這樣的事情可以解決問題,您只需在方法中分配正確的值:
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.