Unity游戲存檔 (將游戲數據儲存至本地文檔)


在Unity中 添加本地文檔儲存游戲數據
首先我們應該在Unity中創建一個C#腳本,將其命名為Inventory
腳本不用掛在任何物體上,只需要在命名空間之前寫一句代碼,如下:

代碼寫好之后保存,在Unity的文件欄中右鍵就會發現,創建文件夾上方多了一個Inventory,就是我們代碼中的menuName ,而創建出來之后,文檔的名字就是 NewItem,也就是我們的 fileName。

如果需要在文檔中存數據,那就需要再代碼中加東西,存什么類型的數據,就加什么類型的變量。
如下:

我們新建一個Item腳本,創建新的NewItem(物品) 將 Item 儲存在NewInventory(背包)中

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

//這里我們重新創建一個文檔,NewItem用作儲存物品信息,剛剛的 NewInventory 儲存背包信息。
[CreateAssetMenu(fileName = "New Item",menuName = "Inventory/New Item")]
public class Item : ScriptableObject {

    public string itemName; //物品名字
    public Sprite itemImage;//物品圖片
    public int itemHeld;	//物品數量
    public string itemInfo;	//物品介紹

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

在 Inventory 中創建一個列表,儲存數據,每一條數據都是一個Item

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(fileName = "New Item", menuName = "Inventory/New Inventory")]
public class Inventory : ScriptableObject {

	//這行新增的就是我們給文檔中儲存的數據類型,比如現在是一個列表的類型
    public List<Item> itemList = new List<Item>();
	
	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

這樣點擊創建出來的NewItem 和 NewInventory 就會發現里面有數據可以改變了。

 

 

 

 用這種方法創建出來的文檔可以使數據儲存在本地中,在Unity中運行游戲,通過撿拾物品改變里面的值,第二次運行之后不會清零。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM