zoukankan      html  css  js  c++  java
  • Unity3d中的PlayerPrefs游戏存档API的扩展

    功能

    在游戏会话中储存和访问游戏存档。这个是持久化数据储存,比如保存游戏记录。

    静态函数

    • DeleteAll
      Removes all keys and values from the preferences. Use with caution. 从游戏存档中删除所有key。请谨慎使用。

    • DeleteKey
      Removes key and its corresponding value from the preferences. 从游戏存档中删除key和它对应的值。

    • GetFloat
      Returns the value corresponding to key in the preference file if it exists. 如果存在,返回游戏存档文件中key对应的浮点数值。

    • GetInt
      Returns the value corresponding to key in the preference file if it exists. 如果存在,返回游戏存档文件中key对应的整数值。

    • GetString
      Returns the value corresponding to key in the preference file if it exists. 如果存在,返回游戏存档文件中key对应的字符串值。

    • HasKey
      Returns true if key exists in the preferences. 如果key在游戏存档中存在,返回true。

    • Save
      Writes all modified preferences to disk. 写入所有修改参数到硬盘。

    • SetFloat
      Sets the value of the preference identified by key. 设置由key确定的浮点数值。

    • SetInt
      Sets the value of the preference identified by key. 设置由key键确定的整数值。

    • SetString
      Sets the value of the preference identified by key. 设置由key确定的字符串值。

    代码:

    • 保存数据
    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); 
    

    PlayerPrefs的存储是有局限的,在unty3D中只支持int,string,float三种数据类型的写和读。

    扩展

    由于vector3是Unity3d中非常常见的数据类型,因此在这里我举例把vector3类型扩展到PlayerPrefs里面.

            /// <summary>
            /// 存储Vector3类型的值
            /// </summary>
            public static bool SetVector3(string key, Vector3 vector)
            {
    	      return SetFloatArray(key, new float[3] { vector.x, vector.y, vector.z });
            }
    
            /// <summary>
            /// 读取Vector3类型的值
            /// </summary>
            public static Vector3 GetVector3(string key)
            {
    	 	   float[] floatArray = GetFloatArray(key);
    		    if (floatArray.Length < 3)
    	            return Vector3.zero;
    		    return new Vector3(floatArray[0], floatArray[1], floatArray[2]);
            }
    

    把上面的代码放到playerprefs原来的代码里面,就能保存和读取Vector3类型的数据了,其他类型的扩展类似,就不贴代码了.

  • 相关阅读:
    事务管理
    QQ邮箱开启SMTP方法如何授权
    基于JavaMail的Java邮件发送:简单邮件发送
    Spring MVC 响应视图(六)
    Spring MVC 数据绑定 (四)
    Spring MVC Spring中的Model (五)
    Spring MVC 拦截器 (十)
    Spring MVC 异常处理 (九)
    Java 骚操作--生成二维码
    Java MD5校验与RSA加密
  • 原文地址:https://www.cnblogs.com/qiaogaojian/p/6702261.html
Copyright © 2011-2022 走看看