using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Chooselitem8 : MonoBehaviour { public GameObject prefab; public Transform PrefabTransform; public Text text; public static Chooselitem8 Instance; public JSONReader JSONReader; public Text Time;// 要改变颜色的Text组件 private bool isRed = false; // 当前颜色是否是红色 private float timeInSeconds; // 当前时间,单位为秒 public GameObject Timeobject; private bool isRunning = true; // 控制计时是否继续运行 public void Start() { Instance = this; InvokeRepeating(nameof(UpdateTimeDisplay), 0f, 1f); } public void CreateItem(int ID) { GameObject newitem = Instantiate(prefab, PrefabTransform); foreach (var item in JSONReader.LanguageDictionary) { Language languageData = item.Value; if (languageData.ID == ID) { text.text = languageData.Text; } } } private void UpdateTimeDisplay() { if (!isRunning) return; // 将时间格式化为 "MM:SS" string formattedTime = FormatTime(timeInSeconds); if (Time != null) { Time.text = formattedTime; } // 增加时间(每秒) timeInSeconds++; // 检查是否达到10秒 if (timeInSeconds >= 12) { isRunning = false; // 停止计时 CancelInvoke(nameof(UpdateTimeDisplay)); // 停止Invoke调用 Timeobject.SetActive(false); } } public void ColorText() { StartCoroutine(ChangeTextColor()); } /// /// 协程:每秒切换Text的颜色 /// private IEnumerator ChangeTextColor() { while (true) { if (Time != null) { // 切换颜色 Time.color = isRed ? Color.white : Color.red; isRed = !isRed; } // 等待1秒 yield return new WaitForSeconds(1f); } } /// /// 格式化时间为 "MM:SS" /// /// 时间(秒) /// 格式化后的时间字符串 private string FormatTime(float time) { int minutes = Mathf.FloorToInt(time / 60); // 分钟 int seconds = Mathf.FloorToInt(time % 60); // 秒 return $"{minutes:00}:{seconds:00}"; } }