[转]Unity3D游戏开发之数据持久化PlayerPrefs的使用

时间:2023-12-27 19:26:49

转自 http://blog.csdn.net/qinyuanpei/article/details/24195977

首先我们来看两段Unity3D中实现数据读写的简单代码吧:

//保存数据
PlayerPrefs.SetString("Name",mName);
PlayerPrefs.SetInt("Age",mAge);
PlayerPrefs.SetFloat("Grade",mGrade)
//读取数据
mName=PlayerPrefs.GetString("Name","DefaultValue");
mAge=PlayerPrefs.GetInt("Age",0);
mGrade=PlayerPrefs.GetFloat("Grade",0F);

通过上面两段代码,我们可以发现两点:
       1、Unity3D中的数据持久化是以键值的形式存储的,可以看作是一个字典。
       2、Unity3D中值是通过键名来读取的,当值不存在时,返回默认值。
       目前,在Unity3D中只支持int、string、float三种数据类型的读取,所以我们可以使用这三种数据类型来存储简单的数据。目前Unity3D中用于数据持久化的类为layerPrefs,主要的类方法有:

static function DeleteAll(): void
描述:从设置文件中移除所有键和值,谨慎的使用它们。 static function DeleteKey(key: string): void
描述:从设置文件中移除key和它对应的值。 static function GetFloat(key: string, defaultValue: float=OF): float
描述:如果存在,返回设置文件中key对应的值.如果不存在,它将返回defaultValue。 static function GetInt(key: string, defaultValue: int): int
描述:返回设置文件中key对应的值,如果存在.如果不存在,它将返回defaultValue。 static function GetString(key: string, defaultValue: string=**): string
描述:返回设置文件中key对应的值,如果存在.如果不存在,它将返回defaultValue. static function HasKey(key: string): bool
描述:在设置文件如果存在key则返回真. static function SetFloat(key: string, value: float): void
描述:设置由key确定的值. static function SetInt(key: string, value: int): void
描述:设置由key确定的值. static function SetString(key: string, value: string): void
描述:设置由key确定的值.