Another way of saving data in Unity3D in a platform-independent way is to use the PlayerPrefs class.
This class works like a hash table, allowing you to store key-value pairs.
The disadvantage of the built-in PlayerPrefs class is that it’s really slow on iOS and even slower on Android. During a test we did on a Google Nexus One, we saved only 6.25 key-value pairs per second. Because we were trying to save over 300 records, this took way too long. Most likely, they are doing file I/O operations for every modification. The current PlayerPrefs class is clearly not designed to handle a larger amount of data.
So we decided to implement our own version of the PlayerPrefs class, allowing faster saving of tuning parameters in our prototypes. Now we’re saving 300+ records almost instantly on on the same device.
If you’re already using the Unity PlayerPrefs class in your project, and you’re looking for an optimization on iOS and Android devices, you can do the following:
- Download our PlayerPrefs.cs file and add it to your project.
- Add the following line at the beginning of the files in which PlayerPrefs is used:
using PlayerPrefs = PreviewLabs.PlayerPrefs;
- Use PlayerPrefs.Flush() to save all values. This can be done after writing a bunch of data, or when the application is quit (in your main game class):
public void OnApplicationQuit() { PlayerPrefs.Flush(); }
To obtain this optimization, we’re keeping a Hashtable and only writing it to a file when Flush() is called.
We’re deliberately not using an XML format to do this, as this would create an overhead unwanted on these lower-end devices.
Changelog
- March 11, 2011: Original article was posted
- April 1, 2014: An article was written, comparing the performance of the PreviewLabs PlayerPrefs with the Unity PlayerPrefs. Read it here.
- April 1, 2014: A major update to the source code was made.
- April 11, 2014: Bug fixes.
Downloads
- Most recent version: April 11, 2014
April 1, 2014 version(bugs)- March 11, 2011 version
