Help with PlayerPrefs, no idea whats wrong here

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Data : MonoBehaviour
{

    public int currentScore;
    // Start is called before the first frame update
    void Start()
    {
        PlayerPrefs.GetInt("Score");
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.L))
        {
            currentScore++;
            SaveScore();
        }
    }
  
    public void SaveScore()
    {
        PlayerPrefs.Save();
        PlayerPrefs.SetInt("Score", currentScore);
    }
}

I’ve looked around on youtube, following people who shows this exact code, why doesn’t it work?
I’ve got an int that adds a score each time I press the L button, its supposed to be saving the int value each time I exit playmode and go back. But the score always starts at 0.

Have I done anything wrong? Would appreciate some help! :slight_smile:

Look in start method. You call method, but doesn’t use returned value.

1 Like

I would highly recommend not splattering string literals around your code like so much confetti.

This pattern works pretty well:

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

https://gist.github.com/kurtdekker/01da815d2dfd336a925ae38019c3a163

Useful for a relatively small number of simple values.

Are you actually intending for this to be persisted from one game launch to the next? If you just want a simple GameManager to store the score between scenes during a game, this might suit you better:

ULTRA-simple static solution to a GameManager:

https://discussions.unity.com/t/855136/6

https://gist.github.com/kurtdekker/50faa0d78cd978375b2fe465d55b282b

Also, @Kurt-Dekker didn’t post his “Tutorials are great!” post, but if you are watching videos over anybody who is even a small bit proficient in Unity and using playerprefs, they certainly did not show this “exact” code. Even looking up Unity’s own example should show what is wrong with your code. https://docs.unity3d.com/ScriptReference/PlayerPrefs.GetInt.html

1 Like