Friday, September 4, 2009

Simple Stream for PlayerPrefs

Hello world!

Today I want to share a little snippet that allows you access PlayerPrefs as if you were reading from, or writing to, a stream. This work resulted from trying to write data to disk from inside the web player using file streams. This is not allowed in web player builds. You can access this code at pastebin.

The problem was that migrating a standalone build to a web player build caused old File accesses to break the code. After some investigation, it seems that the only way I could write player profile data when in web player was to use PlayerPrefs. PlayerPrefs isn't really an ideal structure for saving data due to the flat structure of key/value pairs. Creating internal lists and trees would be hard to do because you'd have to come up with a good convention of naming the keys. Incrementing integers would be one way to go, but I wanted to access PlayerPrefs just as with any other stream of data.

PlayerPrefsStream was born. I figured, that if it was possible to store any arbitrary data in a string, I could just use one key/value pair and write data to an encoded string. I use Base64 encoding to encode binary data to a string, without having to worry about special control characters which might be used internally by UnityEngine. This allows me to write data to a string, and then store that string using a key/value pair in PlayerPrefs.

Some basic testing showed that the code works for data chunks of 0.25 MiB, or less than. I also tried 0.5 MiB, but when I did that test, Unity Editor mysteriously hang without any error messages. I know that the PlayerPrefs file limit on web builds is 1 MiB, but this shouldn't cause any error in the editor. It is mysterious. Perhaps each string value has an upper limit, in which case I need to rewrite the stream code to write to several keys to store data greater than the unknown limit.

If anyone can shed some light on this problem, just write some comments.

No comments:

Post a Comment