Game Development
PlayerPrefs
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.
Exercise Score saving with PlayerPrefs
Define a Start method. Inside, declare int highscore = 500; and print "Kaydedilen skor: " + highscore to the console using Debug.Log.
Show example solution
using UnityEngine;
public class PrefsManager : MonoBehaviour
{
void Start()
{
int highscore = 500;
Debug.Log("Kaydedilen skor: " + highscore);
}
}
Test yourself
-
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
- Compressing 3D model textures and audio clips
Show answer
Simple settings and values like volume or high scores — Because PlayerPrefs only supports int, float, and string types, it is ideal for lightweight preferences and settings.
-
Save integer value
PlayerPrefs.Set____("HighScore", 250);
Show answer
PlayerPrefs.SetInt("HighScore", 250);
-
PlayerPrefs concepts
- PlayerPrefs
- Key-value local storage class
- SetInt
- Method saving integer value
- GetFloat
- Method reading floating-point setting
- Save()
- Call forcing changes to disk immediately
Next lesson: JSON serialization