弊端:需要文件夹设置为共享,只能Windows电脑对Windows电脑
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class NewBehaviourScript : MonoBehaviour
{
public Text text;
string fileUrl = @"file:///\\192.168.1.100\共享文件夹\test.txt";
string savePath = "test.txt";
void Start()
{
if (Application.platform == RuntimePlatform.Android)
{
savePath = "sdcard/test.txt";
}
StartCoroutine(DownloadFile(fileUrl));
}
private IEnumerator DownloadFile(string url)
{
UnityWebRequest request = UnityWebRequest.Get(url);
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
text.text = "下载文件时发生错误: " + request.error;
Debug.LogError("下载文件时发生错误: " + request.error);
}
else
{
File.WriteAllBytes(savePath, request.downloadHandler.data);
text.text = "文件下载完成";
Debug.Log("文件下载完成");
}
}
}