【问题标题】:Unity: How to convert a float value to a 00:00 string?Unity:如何将浮点值转换为 00:00 字符串?
【发布时间】:2018-04-12 16:22:14
【问题描述】:

我有一个在后台运行的计时器,我想在关卡结束时显示排行榜。我想使用这个计时器并将其转换为 00:00 格式 00(分钟):00(秒)(即 01:40)。这怎么可能?我只需要在关卡结束时进行计算和转换。

这就是我现在所拥有的。我正常启动计时器

void Update()
{
    if(timerIsRunning)
    {
        mainGameTimer += Time.deltaTime;
    }
}

现在要以 00:00 格式添加计时器,我需要将其作为浮点数传递,但在排行榜中将其作为字符串读取

public void ShowResult()
{
    int min = Mathf.FloorToInt(mainGameTimer / 60);
    int sec = Mathf.FloorToInt(mainGameTimer % 60);

    users.Add(new User(userName, score , timeScore));
    users.Sort(delegate (User us1, User us2)
    { return us2.GetScore().CompareTo(us1.GetScore()); });
    int max = users.Count <= 10 ? users.Count : 10;
    for (int i = 0; i < max; i++)
    {
        //leaderListName[i].text = users[i].GetName() + "- " + users[i].GetScore() + "-" + Mathf.RoundToInt(users[i].GetTimeScore()) + "Sec";
        leaderListName[i].text = users[i].GetName();
        leaderListscore[i].text = users[i].GetScore().ToString();
        leaderListtime[i].text = users[i].GetTimeScore().ToString();
    }

}

class User
{
    string name;
    int score;
    float timeScore;

    public User(string _name, int _score , float _timeScore)
    {
        name = _name;
        score = _score;
        timeScore = _timeScore;
    }
    public string GetName() { return name; }
    public int GetScore() { return score; }
    public float GetTimeScore() { return timeScore; }
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您可以使用 TimeSpan 转换为时间格式,而不是自己进行计算。输入必须是double 类型:

    double mainGameTimerd = (double)mainGameTimer;
    TimeSpan time = TimeSpan.FromSeconds(mainGameTimerd);
    string displayTime = time.ToString('mm':'ss");
    

    【讨论】:

      【解决方案2】:

      这是我常用的一段代码

      //Calculate the time in minutes and seconds.
      int minutes = (int)levelDuration / 60;
      int seconds = (int)levelDuration % 60;
      
      //Update the duration text.
      durationText.text = minutes.ToString() + ":" + ((seconds < 10) ? ("0") : ("")) + seconds.ToString();
      

      【讨论】:

      • 您可以使用string.Format 而不是使用+ 运算符连接字符串。此外,不需要复杂的条件运算符:只需使用seconds.ToString("00"),它就会以所需的格式返回字符串。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      • 2021-12-21
      • 2021-03-30
      • 2019-10-15
      • 2018-03-23
      • 1970-01-01
      相关资源
      最近更新 更多