Persistent Data Between Scenes: How To Use PlayerPrefs in Unity
I recently made a code-typing tutor game themed as a Wild West adventure.
On the main menu, players select a programming language and difficulty. From these choices, the game generates a shooting gallery from code snippets.
The actual gameplay occurs in a separate scene.
How can we make sure that the language and difficulty selected by the user in the Main Menu persist into the new scene?
PlayerPrefs is a useful built-in utility that makes it easy to persist certain types of data between scenes.
PlayerPrefs is accessed like a hashtable or dictionary.
You can use the included SetString(), SetInt(), or SetFloat() methods to set a key/value pair. Or you can use the GetString(), GetInt(), and GetFloat() to get a value by key.
PlayerPrefs also has a helpful method .HasKey() which will return true or false based on whether a key already exists in the PlayerPrefs.
PlayerPrefs in Practice
For my project, I needed to match .txt files (code snippets for typing practice) with the language and difficulty selected by the user.
Let’s make a function to set our difficulty and language settings:
Using event listeners in Unity, we pass in the appropriate values from whatever button the user selects. Here’s how that looks for setting the language from the Main Menu.
Later, when the project spawns the next scene, we refer to PlayerPrefs.GetString() and retrieve the language and difficulty settings. For our shooting gallery, it tells us which .txt file to use.
Persistence! Our shooting gallery now works in the selected language and difficulty.
Careful: Don’t Use PlayerPrefs For Important Stuff
PlayerPrefs stores data in a plaintext file. This makes it easy to access and to edit. PlayerPrefs would be easy to hack, so never use it to store important data like a player’s experience points or score!
PlayerPrefs is a great, simple tool for storing non-sensitive user information. Happy coding!