我制造了#34; Roll-a-ball"来自Youtube上的Unity教程的游戏。但是,我尝试过编程计数器,这很好。问题是当游戏重新启动时,计时器不会,即使我已手动将其设置为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;
}
}
}
答案 0 :(得分:3)
您只是更新显示输出的文本框,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");
}
}
答案 1 :(得分:2)
您应该使用Time.timeSinceLevelLoad
代替。
Somethig喜欢这样:
float time = Time.timeSinceLevelLoad;
TimeSpan t = TimeSpan.FromSeconds( secs );
timerText.text = t.ToString(@"mm\:ss");