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

  • 相关阅读:
    POJ1741 Tree(树分治)
    codeforces713D Animals and Puzzle(二维倍增)
    codeforces713C Sonya and Problem Wihtout a Legend(dp)
    codeforces724E Goods transportation(最小割——dp)
    codeforces710E Generate a String(dp)
    codeforces Intel Code Challenge Final Round (Div. 1 + Div. 2, Combined) 题解(A-D)
    BNUOJ52317 As Easy As Possible(树上倍增)
    hihocoder1386 Pick Your Players(dp)
    常用函数
    vector总结(更新中。。。)
  • 原文地址:https://www.cnblogs.com/unityworld/p/12960391.html
Copyright © 2011-2022 走看看