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

Nan*_*opl 0 c# unity-game-engine

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

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

void Update()
{
    if(timerIsRunning)
    {
        mainGameTimer += Time.deltaTime;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在要以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; }
}
Run Code Online (Sandbox Code Playgroud)

}

rye*_*oss 5

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

double mainGameTimerd = (double)mainGameTimer;
TimeSpan time = TimeSpan.FromSeconds(mainGameTimerd);
string displayTime = time.ToString('mm':'ss");
Run Code Online (Sandbox Code Playgroud)