obsidian/笔记文件/2.笔记/UniTask读取服务器文本和下载文件 解压文件 示例.md
2025-03-26 00:02:56 +08:00

4.7 KiB
Raw Blame History

#unity/代码缓存

需要注意的是如果要使用到UniTask是需要解压对应的插件库到工程才可以正常使用

!Pasted image 20241107092906.png

解压后,相关的插件文件结构:

!Pasted image 20241107093117.png

需要引用的,命名空间

!Pasted image 20241107093152.png

SDKEditor

using UnityEditor;  
using UnityEngine;  
using UnityEngine.Networking;  
using System;  
using System.Threading.Tasks;  
using System.IO;  
using System.IO.Compression;  
using Cysharp.Threading.Tasks; // 引入 UniTask  
public class SDKEditor : EditorWindow  
{  
    private static SDKEditor _sdkEditor;  
    private string fileUrl = "http://192.168.2.154/XPackage_Data/XPackage/XPackageConfig_Main.txt";  
    private string folderUrl = "http://192.168.2.154/XPackage_Data/XPackage/Library/LiteHTTP.zip"; //服务器文件  
    private string savePath = "Assets/DownloadedFiles/LiteHTTP.zip"; //保存本地文件  
    private string extractPath = "Assets/DownloadedFiles/Extracted";  // 解压到的目标文件夹路径  
    [MenuItem("SDK/SDK编辑器",false)]  
    public static void ShowSDKEditorWindow()  
    {        _sdkEditor = (SDKEditor)GetWindowWithRect(typeof(SDKEditor),new Rect(0,0,550,820),false,"SDK编辑器");  
        _sdkEditor.Show();  
    }  
          
// 启动下载并读取文件  
    public async void StartDownloadAndReadFile()  
    {        string fileContent = await ReadFileFromHttpAsync(fileUrl);  
        Debug.Log("File Content:\n" + fileContent);  
    }  
  
    // 异步读取 HTTP 服务器上的文件内容  
    private async UniTask<string> ReadFileFromHttpAsync(string url)  
    {        // 创建 UnityWebRequest 来获取文本文件内容  
        using (UnityWebRequest request = UnityWebRequest.Get(url))  
        {            // 发送请求并等待响应  
            await request.SendWebRequest().ToUniTask();  
  
            // 检查请求是否成功  
            if (request.result == UnityWebRequest.Result.Success)  
            {                // 返回文件内容  
                return request.downloadHandler.text;  
            }  
            else  
            {  
                // 发生错误,返回错误信息  
                Debug.LogError("Failed to download file: " + request.error);  
                return null;            }  
        }    }          
// 异步下载文件  
    private async UniTask DownloadFileAsync(string url, string localPath)  
    {        using (UnityWebRequest request = UnityWebRequest.Get(url))  
        {            await request.SendWebRequest().ToUniTask();  
  
            if (request.result == UnityWebRequest.Result.Success)  
            {                // 确保目标文件夹存在  
                string directory = Path.GetDirectoryName(localPath);  
                if (!Directory.Exists(directory))  
                {                    Directory.CreateDirectory(directory);  
                }  
  
                // 保存文件  
                File.WriteAllBytes(localPath, request.downloadHandler.data);  
                Debug.Log($"Downloaded file from {url} to {localPath}");  
                await  ExtractZipFileAsync(localPath, extractPath);  
            }  
            else  
            {  
                Debug.LogError("Failed to download file: " + request.error);  
            }  
        }    }  
    // 异步解压文件  
    private async UniTask ExtractZipFileAsync(string zipFilePath, string extractPath)  
    {        // 检查压缩包是否存在  
        if (File.Exists(zipFilePath))  
        {            // 确保目标解压文件夹存在  
            if (!Directory.Exists(extractPath))  
            {                Directory.CreateDirectory(extractPath);  
            }  
  
            // 使用 System.IO.Compression 解压缩文件  
            await UniTask.SwitchToThreadPool();  // 在线程池中执行解压操作,避免阻塞主线程  
            try  
            {  
                ZipFile.ExtractToDirectory(zipFilePath, extractPath);  
                Debug.Log($"Extracted {zipFilePath} to {extractPath}");  
            }  
            catch (System.Exception ex)  
            {                Debug.LogError("Failed to extract zip file: " + ex.Message);  
            }  
            await UniTask.SwitchToMainThread();  // 切换回主线程,更新 UI 或通知用户  
            AssetDatabase.Refresh();  
        }  
        else  
        {  
            Debug.LogError("Zip file not found at: " + zipFilePath);  
        }  
    }      
    private void OnGUI()  
    {        if (GUILayout.Button("Add", GUILayout.Width(100)))  
        {            StartDownloadAndReadFile();  
            DownloadFileAsync(folderUrl, savePath);  
        }  
    }}