untiy 读取csv文件
时间: 2025-07-11 07:46:03 浏览: 10
在 Unity 项目中读取和解析 CSV 文件是一个常见的需求,尤其是在处理配置数据、表格信息或外部资源时。以下介绍几种常见且有效的方法。
### 使用 TextAsset 直接读取
对于小型的 CSV 文件,可以通过 `TextAsset` 类将其作为文本资源加载,然后通过字符串操作进行解析。CSV 文件应放置在 `Resources` 文件夹下以便访问。
```csharp
using UnityEngine;
public class CSVReader : MonoBehaviour
{
public TextAsset csvFile; // 在 Inspector 中拖入你的 CSV 文件
public string[][] dataArray;
void Start()
{
string[] lines = csvFile.text.Split('\n'); // 按行分割
dataArray = new string[lines.Length][];
for (int i = 0; i < lines.Length; i++)
{
dataArray[i] = lines[i].Split(','); // 按逗号分割每行内容
}
// 示例:输出第一行第二列的数据
Debug.Log(dataArray[0][1]);
}
}
```
该方法适用于简单的 CSV 文件结构,并且可以轻松集成到项目中[^2]。
### 使用通用字符串解析器(适合复杂结构)
如果 CSV 文件包含复杂的格式,例如字段中包含逗号或换行符,建议使用更通用的解析方式,比如逐字符解析以识别引号包裹的内容。
```csharp
using System.Collections.Generic;
using UnityEngine;
public class AdvancedCSVReader : MonoBehaviour
{
public TextAsset csvFile;
public List<List<string>> dataRows = new List<List<string>>();
void Start()
{
using (System.IO.StringReader reader = new System.IO.StringReader(csvFile.text))
{
string line;
while ((line = reader.ReadLine()) != null)
{
dataRows.Add(ParseCSVLine(line));
}
}
// 示例:输出第一行第二列的数据
Debug.Log(dataRows[0][1]);
}
List<string> ParseCSVLine(string line)
{
List<string> result = new List<string>();
bool inQuotes = false;
string currentField = "";
foreach (char c in line)
{
if (c == '"')
{
inQuotes = !inQuotes;
}
else if (c == ',' && !inQuotes)
{
result.Add(currentField);
currentField = "";
}
else
{
currentField += c;
}
}
result.Add(currentField); // 添加最后一个字段
return result;
}
}
```
这种方法能够正确处理包含逗号或换行的字段,适合需要高兼容性的场景[^1]。
### 使用第三方库简化开发
Unity 社区中有许多现成的 CSV 解析库,例如 [CsvParser](https://github.com/Forceu/GCsvParser),它们提供了更强大的功能,如类型转换、异步加载等。
```csharp
using CsvParser;
using UnityEngine;
public class CsvParserExample : MonoBehaviour
{
public TextAsset csvFile;
void Start()
{
using (var parser = new CsvParser.CsvParser(new System.IO.StringReader(csvFile.text)))
{
while (parser.Read())
{
for (int i = 0; i < parser.FieldCount; i++)
{
Debug.Log($"Row {parser.LineNumber}, Column {i}: {parser[i]}");
}
}
}
}
}
```
这种方式减少了手动编写解析逻辑的工作量,并提高了代码的健壮性。
---
阅读全文
相关推荐




















