"PlayerPrefs.SetValue" Not Working Properly?

Hey Unity! I’m trying to make a script to count the playtime of the player.

using UnityEngine;
using TMPro;

public class PlaytimeCounter : MonoBehaviour
{
    //Le Variables
    private float playSeconds;
    private float playMinutes;
    private float playHours;
    private float playDays;

    //Starting Value If New
    private const int startTimeCount = 0;

    //Le Displays
    public TextMeshPro SecondsDisplay;
    public TextMeshPro MinutesDisplay;
    public TextMeshPro HoursDisplay;
    public TextMeshPro DaysDisplay;

    void Start()
    {
        //Loads values if exist, else set to starting value
        playSeconds = PlayerPrefs.GetFloat("", startTimeCount);
        playMinutes = PlayerPrefs.GetFloat("", startTimeCount);
        playHours = PlayerPrefs.GetFloat("", startTimeCount);
        playDays = PlayerPrefs.GetFloat("", startTimeCount);
    }

    void Update()
    {
        //Update time
        playSeconds += Time.deltaTime;

        //Update other values if overlap
        if (playSeconds > 59)
        {
            playMinutes += 1;
            playSeconds = 0;
        }
        if (playMinutes > 59)
        {
            playHours += 1;
            playMinutes = 0;
        }
        if (playHours > 23)
        {
            playDays += 1;
            playHours = 0;
        }

        //Save the values
        PlayerPrefs.SetFloat("", playSeconds);
        PlayerPrefs.SetFloat("", playMinutes);
        PlayerPrefs.SetFloat("", playHours);
        PlayerPrefs.SetFloat("", playDays);

        //Update the displays
        int DisplaySeconds = Mathf.CeilToInt(playSeconds);
        SecondsDisplay.text = "Seconds: " + DisplaySeconds.ToString();
        int DisplayMinutes = Mathf.CeilToInt(playMinutes);
        MinutesDisplay.text = "Minutes: " + DisplayMinutes.ToString();
        int DisplayHours = Mathf.CeilToInt(playHours);
        HoursDisplay.text = "Hours: " + DisplayHours.ToString();
        int DisplayDays = Mathf.CeilToInt(playDays);
        DaysDisplay.text = "Days: " + DisplayDays.ToString();
    }
}

For some reason, every time I test this, none of the four values save. Does anyone know why this is?

1 Like

The empty quotes here demonstrate that you haven’t finished writing your code.

If it isn’t immediately clear to you why I say this, go work through some simple PlayerPrefs tutorials rather than trying to make it up as you go. It will save you a lot of time and effort.

After you understand the basics of how to use the PlayerPrefs API, read onto this:

Here’s an example of simple persistent loading/saving values using PlayerPrefs:

Useful for a relatively small number of simple values.

3 Likes

Well spotted, my eyes glossed over that. Maybe my brain was in denial. :slight_smile:

3 Likes