Unity使用CSV读写表格文件

CSV(逗号分隔值文件格式):以纯文本形式存储表格数据。

1.挂载脚本

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

public class RWCsv : MonoBehaviour
{
    public string fileName;
    public List<Student> books = new List<Student>();
    // Start is called before the first frame update
    void Start()
    {
        //文件位置
        string filePath = Application.streamingAssetsPath + "/" + fileName + ".csv";
        //判断目录是否存在
        if(!Directory.Exists(Application.streamingAssetsPath))
        {
            //创建目录
            Directory.CreateDirectory(Application.streamingAssetsPath);
        }
        StreamWriter sw = new StreamWriter(filePath);
        //向文件中写入数据
        sw.WriteLine("Id,Name");
        for(int i=0; i < books.Count; i++)
        {
            sw.WriteLine($"{books[i].id}, {books[i].name}");
        }
        //推送到流文件
        sw.Flush();
        //关闭文件
        sw.Close();
        StreamReader sr=new StreamReader(filePath);
        //读取文件数据
        string str;
        while((str=sr.ReadLine())!=null)
        {
            Debug.Log(str);
        }
        //关闭文件
        sr.Close();
    }

    // Update is called once per frame
    void Update()
    {

    }
}
[System.Serializable]
public class Student
{
    public string id;
    public string name;
}

2.回到unity,在脚本组件上输入数据

3.右击Assets文件夹,点击Refresh,可以看到多出了一个StreamingAssets文件夹和data文件

4.使用记事本打开,可以看到写入的数据(使用excel打开会出现乱码,使用wps不会,这里因为没装wps,就用记事本打开查看)

5.在unity的console中可以看到读取的数据

结语:合抱之木,生于毫末;九层之台,起于累土;千里之行,始于足下。

猜你喜欢

转载自blog.csdn.net/falsedewuxin/article/details/129343443