写一个用Unity 2020中UnityWebRequest读取外部文件夹下最新的txt并将数值写下来的程序
时间: 2024-05-12 18:19:32 浏览: 10
以下是一个示例程序,它使用UnityWebRequest读取外部文件夹下的最新txt文件,并将其中的数值写入游戏对象的文本组件中:
```csharp
using UnityEngine;
using UnityEngine.Networking;
using System.IO;
public class ReadLatestTxtFile : MonoBehaviour
{
public TextMesh textMesh; // 游戏对象的文本组件
void Start()
{
StartCoroutine(LoadLatestTxt());
}
IEnumerator LoadLatestTxt()
{
// 外部文件夹路径
string folderPath = Application.dataPath + "/../ExternalFolder/";
// 获取最新修改的txt文件
DirectoryInfo dir = new DirectoryInfo(folderPath);
FileInfo[] fileInfos = dir.GetFiles("*.txt");
FileInfo latestFile = null;
foreach (FileInfo fileInfo in fileInfos)
{
if (latestFile == null || fileInfo.LastWriteTime > latestFile.LastWriteTime)
{
latestFile = fileInfo;
}
}
if (latestFile == null)
{
Debug.LogError("No txt file found in the external folder!");
yield break;
}
// 读取txt文件内容
UnityWebRequest request = UnityWebRequest.Get("file://" + latestFile.FullName);
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Failed to read the txt file: " + request.error);
yield break;
}
string content = request.downloadHandler.text;
// 提取数值并写入文本组件
float value = 0;
if (float.TryParse(content, out value))
{
textMesh.text = value.ToString();
}
else
{
Debug.LogWarning("The txt file does not contain a valid number!");
yield break;
}
}
}
```
请注意,此示例程序假定您已经在外部文件夹中创建了一个或多个txt文件,并且这些文件中包含一个有效的浮点数。如果没有,程序将会输出错误或警告信息。您需要根据自己的需要修改外部文件夹路径和游戏对象的文本组件。