Now, I know the title seems stupid, but hear (read, whatever) me out. I have a script that times how long it takes for the player to complete a level and saves it as a playerpref. However, to check whether or not the time of the last game was better than the best time, the script looks at the playerpref for the best time. The problem is, when you start the game, you have no high score, and checking the playerpref returns null, which then cannot be used to check whether or not the last game’s time was faster than the best time. Here’s the script (C#):
//Times games and saves the best times to their respective PlayerPrefs
using UnityEngine;
using System.Collections;
public class Timer : MonoBehaviour {
public static float Seconds = 0; //Seconds passed within this minute
public static int Minutes = 0; //Minutes passed
public static string RealTime; //The time in the form of X:YZ
public static float TimeCompare; //The value used to determine if this game's time is better than the previous
public static float LastTime1 = 0; //Fastest time values are zero by default
public static float LastTime2 = 0;
public static float LastTime3 = 0;
public static float LastTime4 = 0;
void Start() //Get the values for the best time of each level
{
LastTime1 = PlayerPrefs.GetFloat("LastTime1");
LastTime2 = PlayerPrefs.GetFloat("LastTime2");
LastTime3 = PlayerPrefs.GetFloat("LastTime3");
LastTime4 = PlayerPrefs.GetFloat("LastTime4");
Seconds = 0f; //Reset Seconds
Minutes = 0; //Reset Minutes
RealTime = null; //Reset RealTime
TimeCompare = 0; //Reset TimeCompare
}
// Update is called once per frame
void Update () {
Seconds = Time.timeSinceLevelLoad - Minutes*60;
if (Seconds >= 60)
{
Minutes += 1; //If 60 seconds have passed, add one to minutes
}
TimeCompare = Time.timeSinceLevelLoad;
RealTime = (Minutes.ToString() + ":" + Seconds.ToString("F0")); //Convert the Minute and Second variables into a readable value
Debug.Log(RealTime);
if (LoadLevel.GameOver == true)
{
if (LoadLevel.Level == 1 && TimeCompare > LastTime1)
{
PlayerPrefs.SetFloat("LastTime1", TimeCompare);
PlayerPrefs.SetString("Level1Time", RealTime);
PlayerPrefs.Save();
}
else if (LoadLevel.Level == 2 && TimeCompare > LastTime2)
{
PlayerPrefs.SetFloat("LastTime2", TimeCompare);
PlayerPrefs.SetString("Level2Time", RealTime);
PlayerPrefs.Save();
}
else if (LoadLevel.Level == 3 && TimeCompare > LastTime3)
{
PlayerPrefs.SetFloat("LastTime3", TimeCompare);
PlayerPrefs.SetString("Level3Time", RealTime);
PlayerPrefs.Save();
}
else if (LoadLevel.Level == 4 && TimeCompare > LastTime4)
{
PlayerPrefs.SetFloat("LastTime4", TimeCompare);
PlayerPrefs.SetString("Level4Time", RealTime);
PlayerPrefs.Save();
}
}
}
}