unity 讀取Txt 資料
阿新 • • 發佈:2021-01-13
技術標籤:unity3d
方法一: 通過 StreamReader()方法讀取;
using System.Collections.Generic; using UnityEngine; using System.IO; using System.Text; public class ReadTxtData : MonoBehaviour { public string _dataPath; List<float> dataList = new List<float>(); StreamReader reader; public List<float> GetTXTList() { dataList.Clear(); reader = new StreamReader(Application.dataPath + "/" + _dataPath + ".txt", Encoding.UTF8); //Asset下 _dataPath string _text; while ((_text = reader.ReadLine()) != null) { dataList.Add(float.Parse(_text)); } reader.Dispose(); reader.Close(); return dataList; } }
遇到問題:當Txt資料中存在空的資料時會報錯;如下:
解決辦法:刪掉空行的資料
方法二:通過字串拿到所有資料,在進行分割;空行資料獲取結果為null
using UnityEngine; using UnityEngine.UI; public class GetTxtData : MonoBehaviour { public static List<string> GetDataInSources(string dataPath) { TextAsset testAssets = Resources.Load(dataPath, typeof(TextAsset)) as TextAsset; //Resources 目錄下 string text = testAssets.text; //讀到所有資料 string[] TextLines = text.Split(new char[] { '\n' }); Debug.Log("Data length is " + TextLines.Length); return new List<string>(TextLines); } } //List<T>(IEnumerable<T>) //初始化 List<T> 類的新例項,該例項包含從指定集合複製的元素並且具有足夠的容量來容納所複製的元素。