(I am a beginner) So I was working on a stopwatch to show your current time and a high score to show your high score, but on the way I got this error message saying: Argument 2: cannot convert from ‘System.TimeSpan’ to ‘int’. Can someone help me?
// Start is called before the first frame update
void Start()
{
bestTimeText.text = PlayerPrefs.GetInt("HighScore", 0).ToString(@"mm\:ss\:fff");
currentTime = 0;
stopwatchActive = true;
}
// Update is called once per frame
public void Update()
{
if(bestTime > currentTime)
{
bestTime = currentTime;
}
if(stopwatchActive == true)
{
currentTime = currentTime + Time.deltaTime;
}
TimeSpan time = TimeSpan.FromSeconds(currentTime);
currentTimeText.text = time.ToString(@"mm\:ss\:fff");
PlayerPrefs.SetInt("HighScore", time);
}
public void StartStopwatch()
{
stopwatchActive = true;
}
public void StopStopwatch()
{
stopwatchActive = false;
}
}
Hi,
First, next time please provide at least a line on which the error occurred (maybe here its obvious but not every time). Then when it comes to an answer, here is the erroneous line PlayerPrefs.SetInt("HighScore", time);
. Method SetInt expects like a method name suggest an integer value, but you are trying to give it TimeSpan type which is a struct full of stuff. The solution is to give it number of seconds like so: PlayerPrefs.SetInt("HighScore", (int)time.TotalSeconds);
, since TotalSeconds is a double value you ahve to cast it to int - “(int)” bit. Now you must remember to transform total seconds to TimeSpan when loading high scores:
int seconds = PlayerPrefs.GetInt("HighScores", 0); TimeSpan bestTime = TimeSpan.FromSeconds(seconds);
@Immortus1 So, it sort of works, my timer works and the highscore is displayed in a time and not just seconds, but the highscore won’t change. It stays on 00:00:000. I have tried my best to find a solution but its not working.
int seconds = PlayerPrefs.GetInt("HighScore", 0);
bestTimeText.text = PlayerPrefs.GetInt("HighScore", 0).ToString();
currentTime = 0;
stopwatchActive = true;
}
// Update is called once per frame
public void Update()
{
if (stopwatchActive == true)
{
currentTime = currentTime + Time.deltaTime;
}
TimeSpan time = TimeSpan.FromSeconds(currentTime);
currentTimeText.text = time.ToString(@"mm\:ss\:fff");
TimeSpan highTime = TimeSpan.FromSeconds(bestTime);
bestTimeText.text = highTime.ToString(@"mm\:ss\:fff");
if((int)time.TotalSeconds < PlayerPrefs.GetInt("HighScore", (int)highTime.TotalSeconds))
{
print("Highscore!");
bestTimeText.text = time.ToString(@"mm\:ss\:fff");
PlayerPrefs.SetInt("HighScore", (int)time.TotalSeconds);
}
PlayerPrefs.SetInt("HighScore", (int)time.TotalSeconds);
}
public void StartStopwatch()
{
stopwatchActive = true;
}
public void StopStopwatch()
{
stopwatchActive = false;
}