重新开始游戏时停止计数计时器
本文关键字:计时器 游戏 重新开始 | 更新日期: 2023-09-27 18:05:40
我从Youtube上的Unity教程中制作了"Roll-a-ball"游戏。然而,我试过编程一个计数定时器,它工作得很好。问题是当游戏重新开始时,计时器没有,它只是继续,即使我手动设置为00:00。
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
countText.text = "Count: " + count.ToString ();
winText.text = "";
restartText.text = "";
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
if (Input.GetKeyDown(KeyCode.Space))
{
Vector3 jump = new Vector3(0.0f, 250.0f, 0.0f);
rb.AddForce(jump);
}
if (restart)
{
if (Input.GetKeyUp(KeyCode.R))
{
Application.LoadLevel(Application.loadedLevel);
timerText.text = minutes.ToString("00") + ":" + seconds.ToString("00"); //HERE
}
}
}
void Update()
{
if (count < 14)
{
minutes = (int)(Time.time / 60f);
seconds = (int)(Time.time % 60f);
timerText.text = minutes.ToString("00") + ":" + seconds.ToString("00");
}
}
void OnTriggerEnter(Collider other){
if (other.gameObject.CompareTag ("Pickup")) {
other.gameObject.SetActive (false);
count = count + 1;
countText.text = "Count: " + count.ToString ();
if (count >= 14){
winText.text = "You win!";
restartText.text = "Press 'R' for Restart";
restart = true;
}
}
}
你只是更新了显示输出的文本框,Time.time
仍然是游戏首次启动的时间。
你应该做的是,当你创建你的PlayerController获得Time.time
的当前值,然后使用该值并在你试图计算游戏运行了多长时间时减去它。
因为你正在重新加载关卡,所以它应该重新初始化脚本,这样你就不需要在关卡重新启动时设置文本框的值。
private float _startTime;
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
countText.text = "Count: " + count.ToString ();
winText.text = "";
restartText.text = "";
_startTime = Time.time; //Save the time the game has been running.
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
if (Input.GetKeyDown(KeyCode.Space))
{
Vector3 jump = new Vector3(0.0f, 250.0f, 0.0f);
rb.AddForce(jump);
}
if (restart)
{
if (Input.GetKeyUp(KeyCode.R))
{
Application.LoadLevel(Application.loadedLevel);
}
}
}
void Update()
{
if (count < 14)
{
minutes = (int)((Time.time - _startTime) / 60f); //Subtract the time from the total time.
seconds = (int)((Time.time - _startTime) % 60f);
timerText.text = minutes.ToString("00") + ":" + seconds.ToString("00");
}
}
您应该使用Time.timeSinceLevelLoad
代替。
像这样:
float time = Time.timeSinceLevelLoad;
TimeSpan t = TimeSpan.FromSeconds( secs );
timerText.text = t.ToString(@"mm':ss");