0
0
Unityframework~10 mins

PlayerPrefs for simple data in Unity - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - PlayerPrefs for simple data
Start
Set Key-Value
Save Data
Retrieve Data
Use Data in Game
End
PlayerPrefs stores simple data as key-value pairs, saving and retrieving values for game use.
Execution Sample
Unity
PlayerPrefs.SetInt("score", 10);
PlayerPrefs.Save();
int score = PlayerPrefs.GetInt("score", 0);
Debug.Log(score);
This code saves an integer score of 10 and then retrieves and prints it.
Execution Table
StepActionKeyValueResult/Output
1SetInt calledscore10Value stored in PlayerPrefs memory
2Save called--Data saved to disk
3GetInt calledscore-Returns 10
4Debug.Log called--Prints 10 to Console
5End--Execution complete
💡 All steps complete, data saved and retrieved successfully.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
scoreundefined10 (in PlayerPrefs memory)10 (saved)10 (retrieved)10 (used)
Key Moments - 2 Insights
Why do we call PlayerPrefs.Save() after SetInt?
PlayerPrefs.SetInt stores data in memory, but PlayerPrefs.Save writes it to disk. Without Save, data might not persist after the game closes (see execution_table step 2).
What happens if the key does not exist when calling GetInt?
GetInt returns the default value provided (0 in this example). This prevents errors and ensures a known value (refer to execution_table step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what value does GetInt return at step 3?
A0
B10
Cnull
DError
💡 Hint
Check the 'Result/Output' column at step 3 in the execution_table.
At which step is the data actually saved to disk?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look for the action 'Save called' in the execution_table.
If we skip PlayerPrefs.Save(), what might happen?
AData is saved anyway
BGame crashes
CData is lost when game closes
DData doubles
💡 Hint
Refer to key_moments explanation about Save importance.
Concept Snapshot
PlayerPrefs stores simple data as key-value pairs.
Use SetInt, SetFloat, SetString to save data.
Call PlayerPrefs.Save() to write data to disk.
Use GetInt, GetFloat, GetString to retrieve data with a default.
Good for small, simple game settings or scores.
Full Transcript
PlayerPrefs is a Unity feature to save simple data like numbers or text. You store data by giving it a key name and a value using SetInt, SetFloat, or SetString. After setting data, you call PlayerPrefs.Save() to make sure it is saved on the device. Later, you can get the data back using GetInt, GetFloat, or GetString by using the same key. If the key does not exist, you get a default value you provide. This is useful for saving scores, settings, or small pieces of information between game sessions.