Unity3D 从 TEXT 文件里读入数组

本文介绍了一个Unity中的脚本,该脚本能够从文本文件中读取数据并将其转换为二维数组。通过使用UnityEngine和System.IO等命名空间,此脚本实现了将特定格式的文本文件内容解析为整数数组的功能。
参考     2D array from text file 

改得如下程序


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 ());
		}
	}
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值