開發環境
unity 2018.3.8f1
Scripting Runtiem Version .NET 3.5
Api Compatibility Level .NET 2.0
1: 在 Assets 文件夾下新建 StreamingAssets 文件夾, 名字不能改動, 這是 unity 的保留目錄, 用於存放 JSON 文件
2: 在 StreamingAssets 文件夾下新建名為 JsonData.JSON 的文件, 並添加數據
{
"key":"value",
"order":"0",
}
3: 添加實體類腳本 (隨便叫啥).cs
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; [Serializable] public class ConfigCOM { public string key; public string order; }
4: 添加腳本 用於讀取外部的 JSON 文件
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; public class CLoadConfig { public static T LoadJsonFromFile<T>() where T : class { if (!File.Exists(Application.dataPath + "/StreamingAssets/ConfigCOM.json")) { Debug.LogError("配置文件路徑不正確"); return null; } StreamReader sr = new StreamReader(Application.dataPath + "/StreamingAssets/ConfigCOM.json"); if (sr == null) { return null; } string json = sr.ReadToEnd(); if (json.Length > 0) { return JsonUtility.FromJson<T>(json); } return null; } }
其中 "/StreamingAssets/ConfigCOM.json" 的意思就是位於 StreamingAssets 目錄下的 ConfigCOM.json 文件
5: 將獲取到的 JSON 數據賦值到需要的地方
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GetJsonValue : MonoBehaviour { public string com; public int order; private void Update() { ConfigCOM configCOM = CLoadConfig.LoadJsonFromFile<ConfigCOM>(); com = configCOM.com; order = configCOM.order; } }
或者直接通過
ConfigCOM configCOM; void function(){ configCOM = CLoadConfig.LoadJsonFromFile<ConfigCOM>(); com = configCOM.com; order = configCOM.order; }
的方式使用數據也是一樣的
這樣一來, 需要在游戲打包運行后再去讀取使用的文件, 就這樣放在 StreamingAssets 文件夾中就可以了
