翻以前别人写的一个项目,看到读取本地配置文件的,目前虽然不太懂,但是先放着,估摸以后牛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);
}
}