Unity顺序读取一个文件下的所有文本文档的名称,每次执行该代码,将读取的文本文档名称与之前读取的文本文档名称进行对比,再次写入时,删除指定路径下的文本文档里面以前读取的数据,只写入与上一次文本文档名称不同的文本文档里面的数据。
时间: 2023-11-22 22:53:26 浏览: 45
以下是一个可以实现你所需功能的Unity C#代码:
```csharp
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class FileHandler : MonoBehaviour
{
private string directoryPath = ""; // 指定路径下的文件夹路径
private List<string> fileNames = new List<string>(); // 文件名列表
private string currentFileName = ""; // 当前处理的文件名
void Start()
{
// 指定路径下的文件夹路径
directoryPath = Application.dataPath + "/TextFiles/";
// 获取指定路径下的所有文本文档的名称
string[] filePaths = Directory.GetFiles(directoryPath, "*.txt", SearchOption.TopDirectoryOnly);
foreach (string filePath in filePaths)
{
fileNames.Add(Path.GetFileNameWithoutExtension(filePath));
}
// 读取当前处理的文件名
currentFileName = PlayerPrefs.GetString("CurrentFileName", "");
}
void Update()
{
// 检查是否需要处理新的文件
if (currentFileName == "" || !fileNames.Contains(currentFileName))
{
if (fileNames.Count > 0)
{
// 找到第一个未处理过的文件名
currentFileName = fileNames[0];
// 删除之前读取的数据
string filePath = directoryPath + currentFileName + ".txt";
if (File.Exists(filePath))
{
File.Delete(filePath);
}
// 将当前处理的文件名写入 PlayerPrefs
PlayerPrefs.SetString("CurrentFileName", currentFileName);
}
}
else
{
// 读取当前处理的文本文档
string filePath = directoryPath + currentFileName + ".txt";
if (File.Exists(filePath))
{
string text = File.ReadAllText(filePath);
Debug.Log(text);
// 处理完当前文本文档后,将当前处理的文件名设为空
currentFileName = "";
PlayerPrefs.SetString("CurrentFileName", currentFileName);
}
}
}
}
```
这段代码会在Start函数中读取指定路径下的所有文本文档的名称,并将当前处理的文件名从PlayerPrefs中读取。然后在Update函数中检查是否需要处理新的文件。如果当前处理的文件名为空,或者已经处理过的文件名列表中不包含当前处理的文件名,就找到第一个未处理过的文件名,并删除之前读取的数据。如果当前处理的文件名不为空,就读取该文件名对应的文本文档,并在处理完之后将当前处理的文件名置为空。
请注意,这段代码只是一个简单的示例,你可能需要根据自己的实际需求进行修改和优化。例如,你可能需要添加错误处理、异常处理、日志记录等功能。