PlayerPrefs functions

From a code point of view, there are functions that allow us to interact with the system. They are all within the PlayerPrefs class, and they are static functions, so you don't need to instantiate a PlayerPref object. Rather, in your code, type PlayerPrefs followed by the name of the function you want to call: PlayerPrefs.NameOfTheFunction(). Obviously, the previous function doesn’t exist, but it was an example of a function call.

Since these functions are not so many, let's see them all. The following three functions (one for each value type) set the pair <key, value>:

  • void SetInt(string key, int value): Stores (or overrides, in case it already exists) an integer value type associated with the key
  • void SetFloat(string key, float value): Stores (or overrides, in case it already exists) a decimal number value type associated with the key
  • void SetString(string key, string value): Stores (or overrides, in case it already exists) a string value type associated with the key

Similar to the preceding three functions, we have the three twin functions that instead of storing, retrieve the values based on the key. Keep in mind that if the key doesn't exist, they return the default value of the type:

  • int GetInt(string key): Retrieves (if it exists) the integer value associated with the key passed as a parameter
  • float GetFloat(string key): Retrieves (if it exists) the decimal number value associated with the key passed as a parameter
  • string GetString(string key): Retrieves (if it exists) the string value associated with the key passed as a parameter

Since we have said that the value might not exist, we have a function to check whether a specific key has an association within a pair:

  • bool HasKey(string key): Returns a Boolean, indicating whether the key passed as the parameter exists or not

Finally, here are a couple of functions to delete the pairs of values:

  • void DeleteKey(string key): Deletes (if it exists) the pair with the key specified as the parameter
  • void DeleteAll(): Erases all the <key, value> pairs, thus erasing all the saved data

There is also a special function that forces the saving of memory. In fact, when we use a set, the save happens only within the context of the application/game, thus improving performance. Although when you close the game, Unity flushes everything in memory and thus saves. However, sometimes you want to force this process to happen before the game is closed (maybe after have saved important data, for example). This can be done with the following function:

  • void Save(): Saves all the <key, value> pairs into the permanent memory
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset