Unity:如何将浮点值转换为00:00字符串?

时间:2018-04-12 16:22:15

标签: c# unity3d

我有一个在后台运行的计时器,在我希望显示排行榜的级别结束时。我想把这个计时器转换为00:00格式00(分钟):00(秒)(即01:40)。怎么可能?我只需要在等级结束时进行计算和转换。

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

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

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

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; }
}

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分: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();