Unity 读取文件 TextAsset读取配置文件方式

这篇文章主要介绍了Unity 读取文件 TextAsset读取配置文件的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

1 支持文件类型

.txt

.html

.htm

.xml

.bytes

.json

.csv

.yaml

.fnt

2 寻找文件

1 //Load texture from disk

 TextAsset bindata= Resources.Load("Texture") as TextAsset; Texture2D tex = new Texture2D(1,1); tex.LoadImage(bindata.bytes); 

2 直接在编辑器中赋值

 public TextAsset textFile;

3 配置文件通常分行配置属性

例如:

英雄名称,等级,生命,攻击

 hero1,1,1,1 hero2,1,1,1 string[] lines = textFile.text.Split("\n"[0]); 可以读出属性 lines[0] = "英雄名称,等级,生命,攻击" lines[1] = "hero1,1,1,1" lines[2] = "hero2,1,1,1"

然后可以读出每条数据的具体属性

 for (int i = 0; i 
 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(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(json); } void LoadMessage() { print(_config.weatherinfo.city); print(_config.weatherinfo.cityid); } } 

以上就是Unity 读取文件 TextAsset读取配置文件方式的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程