23.unity储存文字内容(List、foreach)

今天要用List来储存记事本内的对话资料

0.和昨天一样,先准备好对话.txt

Untitled

1.写脚本,先检查有没有List的命名空间

using System.Collections.Generic;

2.List

//先宣布一个List,型态为<string>,名字为textList
List<string> textList = new List<string>();
//<string>可以改成其他变数型态,也可以设定成class或struct

//在list中添加元素
textList.Add("0-文字内容");
textList.Add("1-文字内容");
textList.Add("2-文字内容");
textList.Add("3-文字内容");

//读取list项目
foreach (var line in textList) //一项一项读取
{
	   Debug.Log(line);
}

脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Control : MonoBehaviour
{

  public TextAsset textFile;        //导入文件

	//new一个List,我取名为textList
  private List<string> textList = new List<string>();

	void GetTextFormFile(TextAsset file)
	    {
	    
	        textList.Clear();//确保List里面没有东西

			//使用字串阵列储存文件内容
	        var lineData = file.text.Split('\n');
            //将字串阵列中的每一项添加到List
	        foreach (var line in lineData) //一项一项读取字串阵列
	        {
	            textList.Add(line);//添加每一项进入List
	        }

			//读取List内资料
	        foreach (var line in textList) //一项一项读取List
	        {
	            Debug.Log(line);
	        }
	    }

        void Start()
    {
        GetTextFormFile(textFile);
        Debug.Log("end");
    }

}

3.结果

2.png

Split更多用法,用更多字符切割文字

能分化成更多小数据,之後可以写成结构或类别

char[] SplitChar ={':','*','\n'};
var lineData = file.text.Split(SplitChar);

3.png


<<:  Scanners API-总金额篇

>>:  Day 08 - Design System x 实作 — Color System

[Day 3] Atomic Operation

前言 昨天简单猜测了非同步框架所应具备的基本功能 ( 某种资料模式, thread schedule...

django新手村13-----路由规则

urls.py str有可以用int path('personal_info<str:name...

伸缩自如的Flask [day 22] pythonanywhere 部署

在我开始介绍Google Cloud Platform的Google app engine之前,我想...

[Day 12] 阿嬷都看得懂的 CSS 收整与 DRY 策略

阿嬷都看得懂的 CSS 收整与 DRY 策略 玫瑰即使换个名字,还是同样芬芳。 -莎士比亚 欢迎各位...

LabVIEW步进马达控制(初阶)

这篇文章使用LabVIEW配合MyRIO进行步进马达的控制,我使用的步进马达是小颗的那种,如果要用扭...