Unity高级功能—本地储存

本地储存的应用场景就是当你的游戏玩耍到一半的时候,退出了,下次进入的时候,还需要之前的状态信息,这个时候就需要用到本地储存。

Unity里面有一个专门的类,来处理这个本地储蓄:PlayerPrefs类

这个类处理的相当于一个键值对:<String name, Value>

主要的处理方法:

    (1) SetInt/SetFloat, SetString:   key-->value

    (2) GetInt/GetFloat, GetString: key-->value;

    (3)DeleteKey/DeleteAll 删除一个key/所有数据;

    (4) HasKey 判断一个Key是否存在;

(5) Save 保存数据;

Eg:

首先我们在游戏运行之前储存我们需要的信息:

using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;  
  
public class localSave : MonoBehaviour  
{  
    // Start is called before the first frame update  
    void Start()  
    {  
        PlayerPrefs.SetInt("关卡",1);  
        PlayerPrefs.SetFloat("血量",25.30f);  
        PlayerPrefs.SetString("关卡名称","牛刀小试");  
        PlayerPrefs.Save();  
    }  
  
    // Update is called once per frame  
    void Update()  
    {  
          
    }  
}  

然后我们运行游戏,运行之后,然后关闭掉,刚才的代码修改成:

using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;  
  
public class localSave : MonoBehaviour  
{  
    // Start is called before the first frame update  
    void Start()  
    {  
        /* 
        PlayerPrefs.SetInt("关卡",1); 
        PlayerPrefs.SetFloat("血量",25.30f); 
        PlayerPrefs.SetString("关卡名称","牛刀小试"); 
        PlayerPrefs.Save(); 
        */  
  
        Debug.Log(PlayerPrefs.GetInt("关卡"));  
        Debug.Log(PlayerPrefs.GetFloat("血量"));  
        Debug.Log(PlayerPrefs.GetString("关卡名称"));  
    }  
  
    // Update is called once per frame  
    void Update()  
    {  
          
    }  
}  

此时我们没有将之前储存数据的部分注释掉,然后直接获取,进行打印。

运行Unity,此时控制台就会将我们之前储存的信息打印出来:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章