Consider this Unity C# code snippet that uses PlayerPrefs:
PlayerPrefs.SetInt("score", 10);
PlayerPrefs.SetString("playerName", "Alex");
int score = PlayerPrefs.GetInt("score");
string name = PlayerPrefs.GetString("playerName");
Debug.Log($"Name: {name}, Score: {score}");What will be printed in the Unity Console?
PlayerPrefs.SetInt("score", 10); PlayerPrefs.SetString("playerName", "Alex"); int score = PlayerPrefs.GetInt("score"); string name = PlayerPrefs.GetString("playerName"); Debug.Log($"Name: {name}, Score: {score}");
PlayerPrefs stores and retrieves data by key. The values set are returned when you get them.
The code sets "score" to 10 and "playerName" to "Alex". Then it retrieves them and prints. So the output is "Name: Alex, Score: 10".
Look at this code snippet:
int level = PlayerPrefs.GetInt("level");
Debug.Log(level);Assuming "level" was never set before, what will be printed?
int level = PlayerPrefs.GetInt("level"); Debug.Log(level);
PlayerPrefs.GetInt returns a default value if the key is missing.
When a key does not exist, PlayerPrefs.GetInt returns 0 by default.
Check this code snippet:
PlayerPrefs.SetInt("lives", 3);
// Missing PlayerPrefs.Save()
// Later in the game, trying to get the value:
int lives = PlayerPrefs.GetInt("lives");
Debug.Log(lives);Why might the value not be saved between game sessions?
PlayerPrefs.SetInt("lives", 3); // Missing PlayerPrefs.Save() // Later in the game, trying to get the value: int lives = PlayerPrefs.GetInt("lives"); Debug.Log(lives);
Think about when PlayerPrefs writes data to permanent storage.
PlayerPrefs.SetInt changes data in memory. To save it permanently, PlayerPrefs.Save() must be called or the application must quit normally.
Which of the following code snippets correctly deletes the PlayerPrefs key "highscore"?
Check the exact method name for deleting a key in PlayerPrefs.
The correct method to delete a key is PlayerPrefs.DeleteKey(string key). Other options are invalid method names.
Consider this sequence of PlayerPrefs commands:
PlayerPrefs.SetInt("coins", 100);
PlayerPrefs.SetString("player", "Sam");
PlayerPrefs.SetFloat("volume", 0.75f);
PlayerPrefs.DeleteKey("coins");
PlayerPrefs.SetInt("coins", 50);How many keys are stored in PlayerPrefs after this code executes?
Think about keys added, deleted, and re-added.
Initially 3 keys are set: "coins", "player", "volume". Then "coins" is deleted and set again. So total keys remain 3.