Unity 简易读取配置文件内容(txt,懒人用)

翻以前别人写的一个项目,看到读取本地配置文件的,目前虽然不太懂,但是先放着,估摸以后牛B了就看懂了

首先自定义一个config类:

using UnityEngine;
using System.Collections;
using System;

[Serializable] //一定要有,同时不能继承MonoBehaviour
public class Config  {
    public int Num1; //我文档里有2个int,2个string类型
    public int Num2;
    public string String1;
    public string String2;
    // Use this for initialization
    void Start () {

}

    private static Config _data;
    public static Config _Data
    {
        get
        {
            if (_data == null)
            {
                string json = System.IO.File.ReadAllText(Application.streamingAssetsPath + "/test.txt");
                _data = JsonUtility.FromJson<Config>(json);
            }
            return _data;
        }
    }   
}

然后在unity 的StreamingAssets文件夹下创建个test.txt

里面内容:(一定要有花括号)

{"Num1":30,"Num2":60,"String1":"aaa","String2":"bbb"}

然后再其他脚本里,直接调用就好了

例如:

using UnityEngine;
using System.Collections;

public class LoadConfig : MonoBehaviour {


// Use this for initialization
void Start () {
        print(Config._Data.Num1);
        print(Config._Data.String2);
    }

// Update is called once per frame
void Update () {

}
}

2017.3.27更新:自己又理解了一点

如果要读取网页某天气信息,但是不止一个花括号,分了几层,需要怎么做?

例如信息:

{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"18","WD":"东南风","WS":"1级","SD":"17%","WSE":"1","time":"17:05","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1011","rain":"0"}}


上面的就不多复述,大概思路就是再建立一个类保存二级信息

Config类修改如下(之前的全部删除):

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;


[Serializable]  //一定要有,同时不能继承MonoBehaviour
public class Config  {
    public Weatherinfo weatherinfo; //这里的weatherinfo 就是上面信息的第一层weatherinfo,建立父级保存信息(名字要对应天气的weatherinfo)
}


[Serializable]
public class Weatherinfo //weatherinfo下的信息保存,类里的city 对应信息里的city,一次类推,我就写2个了;
{
    public string city;
    public int cityid;
}


再新建一个名字为LoadWWW的脚本,用于读取网络的数据:

using UnityEngine;
using System.Collections;
using System;

public class LoadWWW : MonoBehaviour {
    Config _config = new Config();
// Use this for initialization
void Start () {
        StartCoroutine("load");
        Invoke("LoadMessage", 1f);
}

// Update is called once per frame
void Update () {

}

    IEnumerator load()
    {
        WWW w = new WWW("http://www.weather.com.cn/data/sk/101010100.html");//加载某网页数据,根据自己需求改
        yield return w;
        string json = w.text;
        print(json);
        _config = JsonUtility.FromJson<Config>(json);       
    }

    void LoadMessage()
    {
        print(_config.weatherinfo.city);
        print(_config.weatherinfo.cityid);
    }
}

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值