0
0
Unityframework~5 mins

PlayerPrefs for simple data in Unity

Choose your learning style9 modes available
Introduction

PlayerPrefs lets you save small pieces of data like scores or settings so they stay even after you close the game.

Saving the player's high score between game sessions.
Remembering if the player has muted the sound.
Storing the player's chosen character or skin.
Keeping track of simple game settings like difficulty level.
Syntax
Unity
PlayerPrefs.SetInt("key", value);
PlayerPrefs.SetFloat("key", value);
PlayerPrefs.SetString("key", "value");

int score = PlayerPrefs.GetInt("key", defaultValue);
float volume = PlayerPrefs.GetFloat("key", defaultValue);
string name = PlayerPrefs.GetString("key", "default");

PlayerPrefs.Save();

Use SetInt, SetFloat, or SetString to save data.

Use GetInt, GetFloat, or GetString to read data. You can give a default value if the key doesn't exist.

Examples
Saves an integer high score of 100 and reads it back, defaulting to 0 if not found.
Unity
PlayerPrefs.SetInt("HighScore", 100);
int score = PlayerPrefs.GetInt("HighScore", 0);
Saves the player's name as "Alex" and reads it back, defaulting to "Guest" if missing.
Unity
PlayerPrefs.SetString("PlayerName", "Alex");
string name = PlayerPrefs.GetString("PlayerName", "Guest");
Saves a volume level of 0.75 and reads it back, defaulting to 1.0 if not set.
Unity
PlayerPrefs.SetFloat("Volume", 0.75f);
float vol = PlayerPrefs.GetFloat("Volume", 1.0f);
Sample Program

This Unity script saves a high score, player name, and music volume when the game starts. Then it reads them back and prints them to the console.

Unity
using UnityEngine;

public class PlayerPrefsExample : MonoBehaviour
{
    void Start()
    {
        // Save data
        PlayerPrefs.SetInt("HighScore", 250);
        PlayerPrefs.SetString("PlayerName", "Sam");
        PlayerPrefs.SetFloat("MusicVolume", 0.5f);
        PlayerPrefs.Save();

        // Load data
        int highScore = PlayerPrefs.GetInt("HighScore", 0);
        string playerName = PlayerPrefs.GetString("PlayerName", "Unknown");
        float musicVolume = PlayerPrefs.GetFloat("MusicVolume", 1.0f);

        Debug.Log($"High Score: {highScore}");
        Debug.Log($"Player Name: {playerName}");
        Debug.Log($"Music Volume: {musicVolume}");
    }
}
OutputSuccess
Important Notes

PlayerPrefs is best for small, simple data like settings or scores, not big files or complex data.

Always call PlayerPrefs.Save() to make sure data is written to disk immediately.

Data saved with PlayerPrefs stays even if you close and reopen the game.

Summary

PlayerPrefs stores small data like numbers and text between game sessions.

Use Set methods to save and Get methods to load data.

Remember to call PlayerPrefs.Save() to save changes right away.