写一个用Unity中UnityWebRequest读取外部文件夹下最新的txt并将数值写下来的程序
时间: 2024-05-20 12:17:01 浏览: 133
public class ReadLatestTxt : MonoBehaviour
{
public string folderPath;
public Text outputText;
void Start()
{
StartCoroutine(LoadLatestTxt());
}
IEnumerator LoadLatestTxt()
{
// Get all txt files in the folder
string[] fileNames = Directory.GetFiles(folderPath, "*.txt");
// Sort the file names by creation time in ascending order
Array.Sort(fileNames, (a, b) => File.GetCreationTime(a).CompareTo(File.GetCreationTime(b)));
// Get the latest txt file path
string latestTxtPath = fileNames[fileNames.Length - 1];
// Load the text from the latest txt file using UnityWebRequest
UnityWebRequest www = UnityWebRequest.Get("file://" + latestTxtPath);
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.Success)
{
// Parse the text and extract the value
string text = www.downloadHandler.text;
float value = float.Parse(text);
// Display the value in the output text component
outputText.text = value.ToString();
}
else
{
Debug.LogError("Failed to load the latest txt file: " + www.error);
}
}
}
阅读全文