写一个用Unity 2020中UnityWebRequest读取外部文件夹下最新的txt并将数值保存到变量程序
时间: 2024-05-20 20:17:27 浏览: 100
Unity3D脚本:读取外部文件夹的多张JPG图片到材质2
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.IO;
public class ReadLatestTxt : MonoBehaviour
{
public string filePath; // 外部文件夹路径
public string fileName; // txt文件名
public int latestValue; // 最新数值
void Start()
{
StartCoroutine(ReadTxt());
}
IEnumerator ReadTxt()
{
UnityWebRequest www = UnityWebRequest.Get(Path.Combine(filePath, fileName));
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.Success)
{
string txtData = www.downloadHandler.text;
string[] lines = txtData.Split('\n');
string latestLine = lines[lines.Length - 2]; // 倒数第二行为最新数据
int.TryParse(latestLine, out latestValue);
Debug.Log("Latest value: " + latestValue);
}
else
{
Debug.Log("Error: " + www.error);
}
}
}
阅读全文