Copyright (c) 2014 Rawand Fatih, Licensed under MIT License (MIT)
Securely save player preferences in Unity3d projects.
You can use this class to save player preferences in your Unity3d project. When saving a preference, it will be encrypted using DES algorithm. The key that's used for the encryption is different in each device since we generate a random number and add it to the key in initialization for each device.
This also uses Unity3d's native PlayerPrefs classes for saving the values, but encrypts them before hand.
If you are already familiar with Unity3d's PlayerPrefs, with just a little bit of change you can go ahead and use this one!
See PlayerPrefs Docs of Unity3d if you are not familiar with it.
- How To Use
- Methods
- Init()
- isInitialized()
- setLogErrorsEnabled(bool state)
- SetString(string key, string val)
- SetFloat(string key, float val)
- SetInt(string key, int val)
- SetBool(string key, bool val)
- GetString(String key, String defaultValue = "")
- GetInt(String key, int defaultValue = 0)
- GetFloat(String key, float defaultValue)
- GetBool(string key, bool defaultValue = false)
- DeleteKey(string key)
- DeleteAll()
- HasKey(string key)
- Save()
- Contributing
- Contributors
- License
Before diving into details, i'll show you an example and hopefully you'll get what you need. But its also important to know how exactly everything works. Its simple as reading the document bellow ;).
// Initializing the SecurePlayerPrefs
SecurePlayerPrefs.Init();
// Setting a high score but encrypted ;)
SecurePlayerPrefs.SetInt("HIGH_SCORE", 23);
// Getting the highscore back.
int highScore = SecurePlayerPrefs.GetInt("HIGH_SCORE");
// Just setting a string.
SecurePlayerPrefs.SetString("A key name", "This is so simple");
Somewhere before you ever use SecurePlayerPrefs, initialize the keys.
For this you only need to run SecurePlayerPrefs.Init()
in an Awake
or Start
function in
your project or scene.
void Start () {
SecurePlayerPrefs.Init();
}
After this, SecurePlayerPrefs is ready to use.
Download the SecurePlayerPrefs source code and copy it into your project.
Open the code in a editor, and let's modify the your encryption key as following:
- Your DES key is 8 character key of letters, digits, or symbols.
- Your key is devided into three parts:
- Prefix -->
PRIVATE_KEY_PREFIX
- Random (Three Characters) -->
PRIVATE_KEY_RAND
- Suffix -->
PRIVATE_KEY_SUFFIX
- Prefix -->
- Contactinating all three should end up making a 8 letter key. Keep in mind the random part is 3 letters.
- Change those three to what ever you like, see the example:
private static readonly string PRIVATE_KEY_PREFIX = "abcd";
private static readonly string PRIVATE_KEY_RAND = "efg";
private static readonly string PRIVATE_KEY_SUFFIX = "h";
// Or another example.
private static readonly string PRIVATE_KEY_PREFIX = "ab";
private static readonly string PRIVATE_KEY_RAND = "cde";
private static readonly string PRIVATE_KEY_SUFFIX = "fgh";
- We said the random part changes between devices, so each device generates its own random key and saves it in the PlayerPrefs securly encrypted with the key you created up there.
- So now, change the key name that the random key of the device is saved in the PlayerPrefs. Example:
private static readonly string RAND_KEY = "abcdefgh";
GOOD! Everything is ready now!
If you already have a game with player preferences saved and you don't want to lose them, it's fine. You can copy your existing player preferences for the first initialization in a device.
Simply you create an array and call a function we've already provided and the rest is done for you! You add this array and method call under Line 62 of the code where the comment says add your copying code here. Learn from the example:
// Each index has the keyname, a new key name, and the player preference type.
string[,] keyandnewkeys = new string[5, 3] {
{"A_KEY_I_USED", "A_NEW_NAME_FOR_THE_KEY", "int"},
{"ANOTHER_KEY", "ANOTHER_KEY", "int"},
{"HIGHT_SCORE", "fssdes23f", "int"},
{"A_FLOAT_KEY", "A_NEW_FLOAT_KEY", "float"},
{"FINAL_KEY", "STRRRRR", "string"}
};
/*
* The first param is the array of keys, new key names, and the pref type.
* the second is to indicate if the old keys should be removed from the prefs.
*/
securePlayerPrefs(keyandnewkeys, true);
This section we define each function.
public static void Init()
This initializes the keys to be ready to use. If the project is runnin on a device for the first time, it will generate a random 3 digits to add to the key.
You should call this function before using SecurePlayerPrefs anywhere, otherwise it fails.
public static bool isInitialized()
Returns the state of the SecurePlayerPrefs, which tells if its initialized.
public static void setLogErrorsEnabled(bool state)
Setting logErrorsEnabled to ture will print exception stack traces and other logs from the SecurePlayerPrefs.
public static void SetString(string key, string val)
Saves a string in player preferences but securly encrypted by a key identifier.
Parameters:
key
The preference key id.val
The value to set.
public static void SetFloat(string key, float val)
Saves a float in player preferences but securly encrypted by a key identifier.
Parameters:
key
The preference key id.val
The float value to set.
public static void SetInt(string key, int val)
Saves an int in player preferences but securly encrypted by a key identifier.
Parameters:
key
The preference key id.val
The int value to set.
public static void SetBool(string key, bool val)
Saves a boolean in player preferences but securly encrypted by a key identifier.
Parameters:
key
The preference key id.val
The boolean value to set.
public static string GetString(String key, String defaultValue = "")
Returns the decrypted value corresponding to key in the preference file if it exists.
Returns default value defaultValue
if:
- If the key doesn't exist.
- In case of any exceptions.
Parameters:
key
The id of the player preferences.val
The default to return.
You can also leave the defaultValue
parameter, and in this case an empty string will be set as default.
public static int GetInt(String key, int defaultValue = 0)
Returns the decrypted value corresponding to key in the preference file if it exists.
Returns default value defaultValue
if:
- If the key doesn't exist.
- In case of any exceptions.
Parameters:
key
The id of the player preferences.val
The default to return.
You can also leave the defaultValue
parameter, and in this case 0 will be set as default.
public static float GetFloat(String key, float defaultValue = 0.0f)
Returns the decrypted value corresponding to key in the preference file if it exists.
Returns default value defaultValue
if:
- If the key doesn't exist.
- In case of any exceptions.
Parameters:
key
The id of the player preferences.val
The default to return.
You can also leave the defaultValue
parameter, and in this case 0.0f will be set as default.
public static bool GetBool(string key, bool defaultValue = false)
Returns the decrypted value corresponding to key in the preference file if it exists.
Returns default value defaultValue
if:
- If the key doesn't exist.
- In case of any exceptions.
Parameters:
key
The id of the player preferences.val
The default to return.
You can also leave the defaultValue
parameter, and in this case false will be set as default.
public static void DeleteKey(string key)
Removes key and its corresponding value from the preferences. (This is exactly same as PlayerPrefs.DeleteKey)
Parameters:
key
The id of the player preferences.
public static void DeleteAll()
Removes all keys and values from the preferences. (This is exactly same as PlayerPrefs.DeleteAll)
Use with caution.
public static bool HasKey(string key)
Returns true if key exists in the preferences. (This is exactly same as PlayerPrefs.HasKey)
Parameters:
key
The id of the player preferences.
public static void Save()
Writes all modified preferences to disk. (This is exactly same as PlayerPrefs.Save)
By default Unity writes preferences to disk on Application Quit. In case when the game crashes or otherwise prematuraly exits, you might want to write the PlayerPrefs at sensible 'checkpoints' in your game. This function will write to disk potentially causing a small hiccup, therefore it is not recommended to call during actual gameplay.
Do the usual GitHub fork and pull request dance. Add yourself to the contributors section of this file too if you want to.
- Rawand Fatih ([email protected])
## License
The MIT License (MIT)
Copyright (c) 2014 Rawand
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.