unity学习笔记——读写TXT

本文详细介绍了在Unity中如何读写TXT文件的具体实现方法。通过示例代码展示了使用FileInfo和StreamReader进行读取,以及使用StreamWriter进行写入的过程。并演示了如何解析和存储TXT文件中的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

unity学习笔记——读写TXT

先直接贴代码

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

public class ReadTxtManager : MonoBehaviour
{
    private string path = "people";
    public List<People> peopleList = new List<People>();

    void Awake()
    {
        ReadTxt();
        WriteTxt();
        ReadTxt();
    }

    void ReadTxt()
    {
        //1
        TextAsset txt = Resources.Load<TextAsset>(path);//比较简单易懂,适合于只读TXT
        if (txt != null)
        {
			string[] allLine = txt.text.Split('\n');//换行分割每行信息,取到的全部文本在txt.text里
        }


        //2
        FileInfo info = new FileInfo(Application.dataPath + "/Resources/" + path + ".txt");
        if (info.Exists)
        {
            StreamReader reader = info.OpenText();//一般配合写入使用
            string text = reader.ReadToEnd(); //取到的全部文本在reader.ReadToEnd()里,当然也可以使用reader.ReadLine()一行一行取
            Debug.Log(text);
            string[] allLines = text.Split('\n');//换行分割每行信息
            peopleList.Clear();
            for (int i = 1; i < allLines.Length; i++)//从第一行开始,第0行是各列标题
            {
                if (String.IsNullOrEmpty(allLines[i]))
                {
                    continue;//忽略空白行
                }
                string[] line = allLines[i].Split('\t');//制表符分割每项信息
                People peo = new People();
                peo.id = int.Parse(line[0]);
                peo.name = line[1];
                peo.age = int.Parse(line[2]);
                peo.score = int.Parse(line[3]);
                peopleList.Add(peo);//存入列表中
            }
            reader.Dispose();
            reader.Close();//记得在读写后调用关闭,否则会破坏共享
        }
    }

    void WriteTxt()
    {
        FileInfo info = new FileInfo(Application.dataPath + "/Resources/" + path + ".txt");
        StreamWriter writer = null;
        if (info.Exists)
        {
            writer = info.AppendText();
        }
        else
        {
            writer = info.CreateText();//路径不存在则新创建一个TXT
        }
        string line = "5\tddddd\t20\t88";
        writer.WriteLine(line);//写入数据
        writer.Flush();
        writer.Dispose();
        writer.Close();//关闭
    }
}

[Serializable]
public class People
{
    public int id;
    public string name;
    public int age;
    public int score;
}

其中FileInfo StreamWriter 等需要引入System.IO;

TXT表,末尾留一行用来保持格式。


写入后再读取的数据,可以看到已经写入成功了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值