1. 程式人生 > >Unity3D 從 TEXT 檔案裡讀入陣列

Unity3D 從 TEXT 檔案裡讀入陣列

參考    

改得如下程式


FileName.txt

0,1,16,1,1,0
1,1,16,0,0,0
2,1,16,0,0,0
3,1,16,0,1,0
4,1,16,0,0,11
5,1,16,0,0,7
6,1,16,0,1,2
7,1,16,54,48,50
8,1,16,183,138,98
9,1,16,188,169,4
10,1,16,189,189,4
11,1,16,190,189,0
12,1,16,187,146,27
13,1,16,142,113,102
14,1,16,2,1,0
15,1,16,1,1,0
16,1,16,1,0,0
17,1,16,0,0,2
18,1,16,0,1,2
19,1,16,0,1,0
0,2,16,0,0,0
	

程式碼

using UnityEngine;
using System.Collections;
using System.IO;
using UnityEngine.UI;
using System.Collections.Generic;

/**
 * <summary>
 * <para>作者:巨星電藝</para> 
 * <para>編寫日期:巨星電藝</para>
 **/
public class ouyLoadTextArray : MonoBehaviour
{
	public TextAsset txtRawFile;
	public Text uiText; 

	private int[,] spaces;

	private List<string> eachLine;
	private string theWholeFileAsOneLongString;

	// Use this for initialization
	void Start ()
	{

		theWholeFileAsOneLongString = txtRawFile.text;

		eachLine = new List<string>();
		eachLine.AddRange(theWholeFileAsOneLongString.Split("\n"[0]));

		int[,] spaces = new int[eachLine.Count, 6];			// 獲取整數陣列

		for (int i = 0; i < eachLine.Count; i++) {				// 逐行轉換
			string st = eachLine[i];			// 取得一行

			string[] nums = st.Split(new[] { ',' });
			if (nums.Length != 6) {
				Debug.Log ("Misforned input on line "+i+1);
			}

			for (int j = 0; j < Mathf.Min (nums.Length, 6); j++) {
				int val;
				if (int.TryParse (nums[j], out val))
					spaces[i,j] = val;
				else
					spaces[i,j] = -1;
				
			}
		}

		// Output the data to verify the read
		for (int i = 0; i < spaces.GetLength(0); i++) {
			Debug.Log(spaces[i,0].ToString ()+spaces[i,1].ToString()+spaces[i,2].ToString ()+spaces[i,3].ToString()+spaces[i,4].ToString()+spaces[i,5].ToString ());
		}
	}
}