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,此時控制檯就會將我們之前儲存的信息打印出來:

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