unity保存每关的最短通关时间

文章介绍了在Unity项目中,如何使用`LevelManager`类管理关卡的最短通关时间,通过`PlayerPrefs`存储和读取数据,以及`UpdateBestTime`和`FormatTime`方法实现时间的更新和格式化。
摘要由CSDN通过智能技术生成

using UnityEngine;
using UnityEngine.UI;

public class LevelManager : MonoBehaviour
{
    public Text[] timeTexts; // 存储显示时间的文本框
    private float[] bestTimes; // 存储最短通关时间的数组

    void Start()
    {
        // 初始化最短通关时间数组
        bestTimes = new float[timeTexts.Length];

        // 从PlayerPrefs中读取最短通关时间
        for (int i = 0; i < timeTexts.Length; i++)
        {
            bestTimes[i] = PlayerPrefs.GetFloat("BestTime" + i.ToString(), 0f);
            timeTexts[i].text = FormatTime(bestTimes[i]); // 显示最短通关时间
        }
    }

    // 更新最短通关时间
    public void UpdateBestTime(int levelIndex, float time)
    {
        if (time < bestTimes[levelIndex] || bestTimes[levelIndex] == 0f)
        {
            bestTimes[levelIndex] = time;
            PlayerPrefs.SetFloat("BestTime" + levelIndex.ToString(), time);
            timeTexts[levelIndex].text = FormatTime(time); // 更新显示的最短通关时间
        }
    }

    // 格式化时间为分:秒.毫秒的形式
    private string FormatTime(float time)
    {
        int minutes = (int)(time / 60f);
        int seconds = (int)(time % 60f);
        int milliseconds = (int)((time * 1000f) % 1000f);
        return string.Format("{0:00}:{1:00}.{2:000}", minutes, seconds, milliseconds);
    }
}

//关卡对应索引

  for (int i = 0; i < LevelGame.Count; i++)
        {
            if (LevelGame[i].activeSelf)
            {
                TimeAndScoreRecorder.Instance.Index = i;
            }
        }

UpdateBestTime方法在通关时调用,传入关卡的下标和完成的时间

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值