PlayerPrefs
- Game Development course
- Advanced
- Lesson 19/71
- 4 min
Learn simple key-value storage with PlayerPrefs.
Data Storage with PlayerPrefs
PlayerPrefs is a built-in Unity class that stores lightweight user preferences and small data as key-value pairs. It saves entries like audio volume, graphics settings, or high scores in the device's local registry.
// Saving score and volume settings
PlayerPrefs.SetInt("HighScore", 1500);
PlayerPrefs.SetFloat("MasterVolume", 0.8f);
PlayerPrefs.Save();The PlayerPrefs.Save() method explicitly forces any pending in-memory modifications to disk.
Reading Values and PlayerPrefs Limitations
To read saved values, GetInt, GetFloat, and GetString functions are used. A fallback default value can be passed as the second argument if the key does not exist.
// Assigned 0 as the fallback default value
int score = PlayerPrefs.GetInt("HighScore", 0);Because PlayerPrefs is unencrypted and cannot store complex object hierarchies, file-based JSON systems are preferred for comprehensive game saves.
Practice Score saving with PlayerPrefs
Define a Start method. Inside, declare int highscore = 500; and print "Kaydedilen skor: " + highscore to the console using Debug.Log.
Starter code
using UnityEngine;
public class PrefsManager : MonoBehaviour
{
// Start icinde highscore degiskenini tanimla ve yazdir
}Sample solution
using UnityEngine;
public class PrefsManager : MonoBehaviour
{
void Start()
{
int highscore = 500;
Debug.Log("Kaydedilen skor: " + highscore);
}
}Expected output
Kaydedilen skor: 500
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of the following data storage scenarios is PlayerPrefs best suited for?
- Large inventory and quest progression database
- Server-side multiplayer account records
- Simple settings and values like volume or high scores Correct answer
- Compressing 3D model textures and audio clips
Explanation: Because PlayerPrefs only supports int, float, and string types, it is ideal for lightweight preferences and settings.
2 Save integer value
PlayerPrefs.Set____("HighScore", 250);
PlayerPrefs.SetInt("HighScore", 250);
Explanation: The SetInt method is used to persist integer values with PlayerPrefs.
3 PlayerPrefs concepts
| Term | Meaning |
|---|---|
PlayerPrefs |
Key-value local storage class |
SetInt |
Method saving integer value |
GetFloat |
Method reading floating-point setting |
Save() |
Call forcing changes to disk immediately |