Unity 读取Json文件、创建Json文件
1.储存在外部设置
2.Android的时候.json文件没法编辑,可以修改成.txt格式。WPS修改后再改回后缀名。
/// <summary>
/// /storage/emulated/0/ Android 外置内存根目录
/// Application.persistentDataPath; 来检测Android 外置内存根目录的方法
/// </summary>
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Json; using System.Text; using System.Xml; using UnityEngine; using UnityEngine.UI; public class ReadJson:MonoBehaviour { public static TestSetting test = new TestSetting(); //文件路径 public static string JsonPath; public static int Port; public static int CutTime; public static int exeX; public static int exeY; public static int exeWhith; public static int exeHeight; public static string IP; public static string str; public static string AndroidDirectory = "/storage/emulated/0/Android/资源/配置文件/";//安卓路径 public static string WindowsDirectory = System.Environment.CurrentDirectory + "/资源/配置文件/";//Windows路径 [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)] public static void Start() { #if UNITY_ANDROID str = "这里是安卓设备"; Debug.Log("这里是安卓设备"); // Android设置 if(Directory.Exists(AndroidDirectory)) { JsonPath = AndroidDirectory + "Config.json"; } else if(!Directory.Exists(AndroidDirectory)) { Directory.CreateDirectory(AndroidDirectory);//不存在则创建 StreamWriter sw = new StreamWriter(AndroidDirectory + "Config.json"); sw.WriteLine("{\r\n \"Port\": \"10086\",\r\n \"IP\": \"192.168.0.6\",\r\n \"CutTime\": \"0\",\r\n \"exeX\": \"0\",\r\n \"exeY\": \"0\",\r\n \"exeWhith\": \"1920\",\r\n \"exeHeight\": \"1080\"\r\n}"); sw.Close(); JsonPath = AndroidDirectory + "Config.json"; } #endif #if UNITY_STANDALONE_WIN Debug.Log("我是从Windows的电脑上运行的"); str = "我是从Windows的电脑上运行的"; // Windows设置 if(Directory.Exists(WindowsDirectory)) { JsonPath = WindowsDirectory + "Config.json"; } else if(!Directory.Exists(WindowsDirectory)) { Directory.CreateDirectory(WindowsDirectory);//不存在则创建 StreamWriter sw = new StreamWriter(WindowsDirectory + "Config.json"); sw.WriteLine("{\r\n \"Port\": \"10086\",\r\n \"IP\": \"192.168.0.6\",\r\n \"CutTime\": \"0\",\r\n \"exeX\": \"0\",\r\n \"exeY\": \"0\",\r\n \"exeWhith\": \"1920\",\r\n \"exeHeight\": \"1080\"\r\n}"); sw.Close(); JsonPath = WindowsDirectory + "Config.json"; } #endif ReadMyJson(); } //读取方法 public static void ReadMyJson() { string jsonString = File.ReadAllText(JsonPath); TestSetting mytest = JsonUtility.FromJson<TestSetting>(jsonString); test = mytest; Port = mytest.Port; CutTime = mytest.CutTime; exeX = mytest.exeX; exeY = mytest.exeY; exeWhith = mytest.exeWhith; exeHeight = mytest.exeHeight; IP = mytest.IP; print("端口号:" + Port); print("倒计时:" + CutTime); } } //数据类型,用来存储从json中读到的键值对 public struct TestSetting { public int Port; public int CutTime; public int exeX; public int exeY; public int exeWhith; public int exeHeight; public string IP; }
posted on 2023-02-22 16:29 zqiang0803 阅读(268) 评论(0) 编辑 收藏 举报