zoukankan      html  css  js  c++  java
  • [Unity] Unity 读取 JSON 文件(编辑模式和打包后)

    开发环境

      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  文件夹中就可以了

  • 相关阅读:
    洛谷 P3138 [USACO16FEB]Load Balancing S(二维前缀和,离散化)
    洛谷 P1052 [NOIP2005 提高组] 过河(dp,数学)
    洛谷 P1955 [NOI2015] 程序自动分析(并查集,离散化)
    洛谷 P3258 [JLOI2014]松鼠的新家(树上差分,lca)
    洛谷 P2296 [NOIP2014 提高组] 寻找道路(反图bfs)
    洛谷 P4141 消失之物(dp方案数)
    洛谷 P5322 [BJOI2019]排兵布阵(dp,分组背包)
    回溯算法
    分治法
    分支限界法
  • 原文地址:https://www.cnblogs.com/unityworld/p/12960391.html
Copyright © 2011-2022 走看看