文章首發於:http://www.xtstarry.top/index.php/博客/
--------------------------------------------------------------------------------------------------------------------------------------------------------------
科普時間:
LitJSON是一個使用C#編寫的.NET庫,我們可以通過它來處理JSON數據。
JSON(JavaScript Object Notation, JS 對象簡譜) 是一種輕量級的數據交換格式。它基於 ECMAScript (歐洲計算機協會制定的js規範)的一個子集,採用完全獨立於編程語言的文本格式來存儲和表示數據。簡潔和清晰的層次結構使得 JSON 成爲理想的數據交換語言。 易於人閱讀和編寫,同時也易於機器解析和生成,並有效地提升網絡傳輸效率。
爲什麼要使用JSON?
如果使用C#腳本的方式存儲遊戲內的對象數據(比如人物的基礎血量、裝備的名稱/屬性/說明、任務信息),不但不方便統管理,還不適合非技術人員(策劃、美術等)進行添加、修改。
而使用JSON則可以避免這些問題。
如何操作:
首先,下載LitJson.dll文件,導入Unity工程中,我們就能像使用其他包一樣使用LitJson了:
using LitJson;
我們接着在工程中創建一個JSON文件(Unity本身不支持直接創建,我們可以打開資源管理器創建)。
這裏我創建的文件爲:
items.json
我們打開剛剛創建的JSON文件,向裏面添加信息:
[
{
"id": 0,
"title": "手槍",
"value": 1,
"description": "一把簡易的手槍。"
},
{
"id": 1,
"title": "衝鋒槍",
"value": 2,
"description": "一把簡易的衝鋒槍。"
}
]
JSON的語法非常簡單。上面的代碼創建了一個擁有兩個條目的數組,每個條目包含id、title、value、description四個內容。詳細的語法大家可以百度瞭解。
接着我們通過C#腳本來將JSON讀取並保存到對象中:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System.IO;
public class ItemDatabase : MonoBehaviour {
// 用於存儲讀取的JSON數據
private JsonData itemData;
// 用於分開保存剛剛讀取的數據
private List<Item> database = new List<Item>();
void Start () {
// 讀取數據,存入itemData,注意我將items.json放在根目錄,放在其他地方的話記得改參數
itemData = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/items.json"));
// 構建數據庫
ConsructItemDatabase();
// 這兩條Debug信息用來檢測我們的工作成果
Debug.Log(database[0].Description);
Debug.Log(FetchItemByID(0).Title);
}
// 數據庫構建函數
void ConsructItemDatabase()
{
// 遍歷itemData
for(int i = 0;i<itemData.Count;i++)
{
// 一個個將itemData的數據存入database
database.Add(new Item(
(int)itemData[i]["id"],
itemData[i]["title"].ToString(),
(int)itemData[i]["value"],
itemData[i]["description"].ToString()));
}
}
// 通過ID讀取數據
public Item FetchItemByID(int _id)
{
// 遍歷database
for(int i=0;i<database.Count;i++)
{
// 查找ID
if(_id == database[i].ID)
{
return database[i];
}
}
// 找不到返回null
return null;
}
}
// 用於存儲對象信息,每一個值都和JSON中的內容對應
public class Item
{
public int ID { get; set; }
public string Title { get; set; }
public int Value { get; set; }
public string Description { get; set; }
// 構造函數
public Item(int _id,string _title,int _value,string _description)
{
ID = _id;
Title = _title;
Value = _value;
Description = _description;
}
}