c# "Stop Timer" save time is not saving and key is not storing

Hi,
i want to make a button, with this button i want to save the time from my timer:

  if (GUI.Button(new Rect(150, 10, 60, 30), "Stop")) //left down width height
        {
            StopMainTimer();
            float elapsedTime = _mainTimer; //timePlayTime
            string timeKey = Application.loadedLevelName + "_time";
       

            if (PlayerPrefs.HasKey(timeKey))
            {
                float previousTime = PlayerPrefs.GetFloat(timeKey);
                if (elapsedTime < previousTime)
                {
                    PlayerPrefs.SetFloat(timeKey, elapsedTime);
                }
                else
                {
                    PlayerPrefs.SetFloat(timeKey, elapsedTime);
                }
                print("Time: " + elapsedTime);


            }
        }

I do not find an error in this script, it should be print the elapsedTime, but it does not.
The MainTimer is stopping and removed from the GUI… Did i miss something here?
Also the timekey is not set in the registry.

One thing I notice is that you set the key to elapsedTime no matter what.

i replace:
float elapsedTime = _mainTimer; //timePlayTime
with
float elapsedTime = Time.time - _mainTimer; //timePlayTime

but the same issue :frowning:

This part:

…is setting the key whether time has elapsed or not, my guess is take out the first SetFloat line, leave the second one in, hope this helps! :slight_smile:

if(PlayerPrefs.HasKey(timeKey))If you have never successfully saved to PlayerPrefs, this key never gets made. So you never get to continue to save to PlayerPrefs thus the key is still not made.

Looking at the code, I think you attached your else to the wrong if statement. I reordered your brackets around a little.

if (PlayerPrefs.HasKey(timeKey))
{
  // Player has a previous fastest time. See if we beat it.
  float previousTime = PlayerPrefs.GetFloat(timeKey);
  if (elapsedTime < previousTime) // Beat previous time!
    PlayerPrefs.SetFloat(timeKey, elapsedTime);
}
else // Player has no time saved
{
  PlayerPrefs.SetFloat(timeKey, elapsedTime);
}

I will check this, thx.