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

  • 相关阅读:
    怪怪设计论闲谈篇:职责与解耦的矛盾
    知识传播与社区讨论 : 兜售狗皮膏药的"软件先知"
    反弹和补遗:再论Bjarne Stroustrup的"基于对象"的含义
    回帖整理: 领域建模/表模块,Java/.NET 社区风格
    贫血或职责的讨论
    近期可能会研究和讨论的个人动向
    CLR寄宿(上) MSCOREE.DLL
    代码组(2) 成员条件
    说说emit(中)ILGenerator
    CLR寄宿(下) 托管宿主
  • 原文地址:https://www.cnblogs.com/unityworld/p/12960391.html
Copyright © 2020-2023  润新知