0
0
Unityframework~5 mins

Why persistence stores player progress in Unity

Choose your learning style9 modes available
Introduction

Persistence saves the player's progress so they can continue the game later without losing their achievements or items.

When a player finishes a level and you want to save their score.
When a player collects items or upgrades that should be kept for next time.
When a player customizes their character and wants to keep those changes.
When the game needs to remember settings like sound volume or difficulty.
When you want to allow players to pause and resume the game later.
Syntax
Unity
PlayerPrefs.SetInt("level", 3);
PlayerPrefs.Save();

int level = PlayerPrefs.GetInt("level", 1);

PlayerPrefs is a simple way to save small data like numbers or strings.

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

Examples
Saves the player's score as 1500.
Unity
PlayerPrefs.SetInt("score", 1500);
PlayerPrefs.Save();
Loads the saved score or returns 0 if no score was saved yet.
Unity
int score = PlayerPrefs.GetInt("score", 0);
Saves the player's name as "Alex".
Unity
PlayerPrefs.SetString("playerName", "Alex");
PlayerPrefs.Save();
Loads the player's name or uses "Guest" if none was saved.
Unity
string name = PlayerPrefs.GetString("playerName", "Guest");
Sample Program

This program saves the player's level as 5 and then loads it back to show it in the console.

Unity
using UnityEngine;

public class SaveLoadExample : MonoBehaviour
{
    void Start()
    {
        // Save player level
        PlayerPrefs.SetInt("playerLevel", 5);
        PlayerPrefs.Save();

        // Load player level
        int level = PlayerPrefs.GetInt("playerLevel", 1);
        Debug.Log($"Player level is {level}");
    }
}
OutputSuccess
Important Notes

PlayerPrefs is good for small data but not for big or complex data like full game states.

For bigger data, consider using files or databases.

Remember to test saving and loading on the actual device or platform.

Summary

Persistence keeps player progress safe between game sessions.

PlayerPrefs is an easy way to save simple data like scores or settings.

Always save data after setting it to avoid losing progress.