2017-07-13 53 views
2

我要把它改变的.text以下格式:Unity3D C#计时器显示以毫秒为单位

00:00:00

而是我得到 0:00.00000 做什么,我需要更改以纠正我的代码?

private void Update() 
{ 
    if (!chestButton.IsInteractable()) 
    { 
     if (IsChestReady()) { 
      chestButton.interactable = true; 
      chestTimer.SetActive (false); 
      chestTimerBg.SetActive (false); 
      newGift.SetActive (true); 
      return; 
     } 
     //Set Timer 
     ulong diff = ((ulong)DateTime.Now.Ticks - lastChestOpen); 
     ulong m = diff/TimeSpan.TicksPerMillisecond; 
     float secondsLeft = (float)(msToWait - m)/1000.0f; 

     string r = " "; 
     //Hours 
     r += ((int)secondsLeft/3600).ToString() + ": "; 
     secondsLeft -= ((int)secondsLeft/3600) * 3600; 
     //Minutes 
     r += ((int)secondsLeft/60).ToString(); 
     //Seconds 
     r += (secondsLeft % 60).ToString(); 
     chestTimerTxt.text = r; 

    } 
} 

回答

7

您忘记了秒数的整数转换。

r += ((int)secondsLeft % 60).ToString(); 

但是,最简单的做法是使用TimeSpan。

TimeSpan ts = TimeSpan.FromSeconds((int)secondsLeft); 
chestTimerTxt.text = ts.ToString(@"hh\:mm\:ss"); 

如果你试图做手工,你做对了,你还必须检查的情况下,你需要添加一个额外的0或不 - 例如,如果secondsLeft = 50 VS 9.如果你仍然想这样做,然后在做所有计算之前尝试将secondsLeft转换为Int(使用Math.Round向上或向下舍入)。您还需要在分钟和秒之间添加“:”。

相关问题