-2
ShowRestartDialog()中的我的倒數計時器表現時髦。而不是從定義的countdownLength(設置爲5)開始,它從一個隨機負數開始並從那裏開始。爲什麼會這樣呢?謝謝!從隨機負數開始的倒計時
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class CountdownTimer : MonoBehaviour
{
public static CountdownTimer countdownTimerInstance = null; // Create Singleton
public Object startingScene;
public GameObject timeOutWarningDialog;
private GameObject timerDialogBoxInstance;
private GameObject canvas;
private IEnumerator counter;
private Button stopCountButton;
private Text timerTextField;
public float countdownLength;
public float countdownDelay;
private float countdownInterval = 1.0f;
void Awake()
{
if (countdownTimerInstance == null)
countdownTimerInstance = this;
else if (countdownTimerInstance != null)
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}
public void StartPreCountTimer()
{
GameManager.preCountActive = true;
Debug.Log("StartPreCountTimer Timer has Started!");
if (GameManager.restartWarningActive == false)
Invoke("ShowRestartDialog", countdownDelay);
}
public void RestartPreCountTimer()
{
GameManager.preCountActive = false;
Debug.Log("StartPreCountTimer Timer has Restarted!");
CancelInvoke("ShowRestartDialog");
}
void ShowRestartDialog()
{
GameManager.preCountActive = false;
canvas = GameObject.FindGameObjectWithTag("Canvas");
timerDialogBoxInstance = Instantiate(timeOutWarningDialog); // instantiate timeout warning dialog
timerDialogBoxInstance.transform.SetParent(canvas.transform, false);
timerDialogBoxInstance.SetActive(true);
Text[] textFields = timerDialogBoxInstance.GetComponentsInChildren<Text>(true); // get reference to timer textfields
timerTextField = textFields[2]; // access and assign countdown textfield
stopCountButton = timerDialogBoxInstance.GetComponentInChildren<Button>(); // get reference to keep playing button
stopCountButton.onClick.AddListener(StopDialogTimer); // add button listener
if (timerDialogBoxInstance.activeInHierarchy == true)
InvokeRepeating("StartDialogTimer", 0, countdownInterval);
}
void StartDialogTimer()
{
float s = countdownLength--;
Debug.Log(s);
if (timerTextField != null)
timerTextField.text = s.ToString();
if (s == -1)
{
RestartGame();
}
}
void StopDialogTimer()
{
Debug.Log("Restart Cancelled");
CancelInvoke("StartDialogTimer");
Destroy(timerDialogBoxInstance);
}
void RestartGame()
{
SceneManager.LoadScene(startingScene.name);
}
}
「countdownLength(被設定爲5)」 - 是不是在你的代碼實現。你不要初始化它。因此它被設置爲0. – jross
我甚至沒有在您發佈的代碼中看到文字'5' _anywhere_。如果你需要幫助,可以發佈一個很好的[mcve],它能夠真實地再現你聲稱發生的行爲。上面的代碼並不是最小的,它也沒有實際做你聲稱它做的事情。 –
它不是隨機的。隨着遊戲計時器開始,並且每秒都向後計數。 –