对于游戏存档,储存最高分,排行榜都需要用到储存,现在存储的方式有很多,可以存本地的Json,XML,Sqlite,还有一种就是unity自带的一种存储PlayerPrefs。
那么这个PlayerPrefs如何使用呢?
其实很简单,官方的API是里介绍了:
1、PlayerPrefs可以理解为持久化储存,还可以理解为游戏存档, 玩RPG游戏的时候肯定会有游戏存档 存档中就会记录玩家以前游戏的过程,这些都是以数据的形式存在PlayerPrefs中的。
2、在Mac OS X上PlayerPrefs存储在~/Library/PlayerPrefs文件夹,名为unity.[company name].[product name].plist,这里company和product名是在Project Setting中设置的,相同的plist用于在编辑器中运行的工程和独立模式.
3、在Windows独立模式下,PlayerPrefs被存储在注册表的 HKCU\Software\[company name]\[product name]键下,这里company和product名是在Project Setting中设置的.
4、在Web模式,PlayerPrefs存储在Mac OS X的二进制文件 ~/Library/Preferences/Unity/WebPlayerPrefs中和Windows的 %APPDATA%\Unity\WebPlayerPrefs中,一个游戏存档文件对应一个web播放器URL并且文件大小被限制为1MB。如果超出这个限制,SetInt、SetFloat和SetString将不会存储值并抛出一个PlayerPrefsException。
Class Functions类函数
-
Sets the value of the preference identified by key.
设置由key确定的参数值。 -
Returns the value corresponding to key in the preference file if it exists.
如果存在,返回偏好文件中key对应的值。 -
Sets the value of the preference identified by key.
设置由key确定的参数值。 -
Returns the value corresponding to key in the preference file if it exists.
如果存在,返回游戏存档文件中key对应的值。 -
Sets the value of the preference identified by key.
设置由key确定的参数值。 -
Returns the value corresponding to key in the preference file if it exists.
如果存在,返回游戏存档文件中key对应的值。 -
Returns true if key exists in the preferences.
如果key在游戏存档中存在,返回true。 -
Removes key and its corresponding value from the preferences.
从游戏存档中删除key和它对应的值。
-
Removes all keys and values from the preferences. Use with caution.
从偏好中删除所有key。请谨慎使用。 -
Writes all modified preferences to disk.
写入所有修改参数到硬盘。
代码很简单:
这里我们可以得出:
1、Unity3D中的数据持久化是以键值对的形式存储的,可以看做一个字典。
2、unity3D中的值通过键名来读取的,当值不存在时,返回默认值。
下面通过一个例子来学习:
第一步,新建一个场景scene1,给其添加脚本,我这里是挂在摄像机上了。用于保存数据。
保存一下,新建场景scene2,同样给给其挂一个脚本用于读取数据。
保存场景,在BuidingSetting里添加场景。运行scene1,可以跳转到scene2里,数据就显示出来了,scene2里点击清除,再打开scene2就会出现默认的值
点击提交数据:
点击清除数据,再重新打开scene2,