たとえば現実世界の15分でゲーム内の1日が経過する、といったゲーム内の経過時間を表示するプログラム。昼と夜で文字やイメージの色が変わります。
ChatGPT-4で出力したコードに、少し改変を加えたものです。
コード
GameDayNightCycle.cs
using UnityEngine; using UnityEngine.UI; using TMPro; // ChatGPT-4 2023/5/8 // ゲーム開始からのゲーム内時間を表示する // 日にち・昼夜表示つき public class GameDayNightCycle : MonoBehaviour { public TextMeshProUGUI timerText; public TextMeshProUGUI dayText; public TextMeshProUGUI ampmText; public Image ampmColorImage; private float dayDuration = 15f * 60f; // 15分で1日が経過 private float timeOfDay; private int dayCount; private bool isDaytime; void Start() { timeOfDay = 0f; dayCount = 1; isDaytime = true; UpdateDayText(); } void Update() { timeOfDay += Time.deltaTime / dayDuration; if (timeOfDay >= 1f) { timeOfDay -= 1f; dayCount++; UpdateDayText(); } int minutes = Mathf.FloorToInt(timeOfDay * 1440f) % 60; int hours = Mathf.FloorToInt(timeOfDay * 1440f / 60f) % 24; timerText.text = hours.ToString("00") + ":" + minutes.ToString("00"); if (hours >= 6 && hours < 18) { isDaytime = true; ampmText.text = "AM"; } else { isDaytime = false; ampmText.text = "PM"; } UpdateDaytimeText(); } void UpdateDayText() { dayText.text = "Day " + dayCount.ToString(); } void UpdateDaytimeText() { if (isDaytime) { timerText.color = new Color32(255, 255, 255, 255); ampmText.color = new Color32(255, 255, 255, 255); ampmColorImage.color = new Color32(0, 0, 0, 255); } else { timerText.color = new Color32(255, 200, 0, 255); ampmText.color = new Color32(255, 200, 0, 255); ampmColorImage.color = new Color32(0, 0, 0, 100); } } }
たとえば、15行目の dayDuration = 15f * 60f;
の 15f を 1f にすれば 現実世界の1分でゲーム内の1日が経過します。
コンポーネント(Inspector)
以下のコンポーネントが作成できます。
変数名 | UIコンポーネント | 説明 |
---|---|---|
Timer Text | TextMeshProUGUI | ゲーム内経過 時間:分 |
Day Text | 〃 | ゲーム内経過日 |
AmPm Text | 〃 | ゲーム内AM/PM |
AmPm Color Image | Image | ゲーム内昼夜(カラーイメージ) |
動作例
時間:分:秒で表示してくれます。