Hello. I’ve been trying to have a time based high score in my game and so far I’ve been able to save my time when finishing a level and displaying it using player.prefs. The problem I’m facing now is that I don’t know how to save a high score that would replace the current time that I already have on a level. For example, when a player finishes a level it would compare the new time to the previous time and if it’s better it will save the new one if it’s worse it will discard it. Here’s the script I’m using for my timer
public class StopWatch : MonoBehaviour
{
public float timeStart;
public Text textBox;
public float seconds, minutes, milliseconds, hours;
bool timerActive = true;
// Use this for initialization
void Start()
{
textBox.text = timeStart.ToString("F2");
}
// Update is called once per frame
void Update()
{
if (timerActive)
{
hours = (int)(Time.timeSinceLevelLoad / 3600f);
milliseconds = (int)(Time.timeSinceLevelLoad * 1000f) % 1000;
minutes = (int)(Time.timeSinceLevelLoad / 60f) % 60;
seconds = (int)(Time.time % 60f);
textBox.text = hours.ToString("00") + ":" + minutes.ToString("00") + ":" + seconds.ToString("00") + ":" + milliseconds.ToString("00");
}
}
and here is the code I’m using to save the time to player.prefs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveTime : MonoBehaviour
{
public Text Time;
string _currenttime;
public void SetTime()
{
_currenttime = Time.text;
PlayerPrefs.SetString("Time", _currenttime);
Debug.Log ("Your Time Is " + PlayerPrefs.GetString("Time"));
}
}
If anyone could help me or guide me in the right direction I would greatly appreciate it.