unity 文件下载到外存

本文介绍如何使用Unity 2017.3的新特性UnityWebRequest的DownloadHandlerFile功能,简洁地实现将assetbundle文件下载到外部存储,并讨论如何将StreamingAssets中的文件复制到persistentDataPath,因为移动设备的C# IO库无法直接读取StreamingAssets内容。同时提到了UnityWebRequest在2017.2版本增加的timeout属性,用于设置下载超时时间。

这个脚本是用来下载assetbuild的 unity2017.3的UnityWebRequest新增了DownloadHandlerFile的支持函数,可以直接将文件下载到外存(可以少写很多代码),也用来把StreamingAssets里的文件复制到persistentDataPath(在移动端C#的IO库好像读不了StreamingAssets里的文件)

*unity2017.2的UnityWebRequest新增timeout属性,用来设置超时时间(又可以少写很多代码)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System;
using System.IO;

public class ABDownLoad : MonoBehaviour 
{
	float m_downCount=0;
	public void Download(string _newFileIP, string _newFilesPath,string _oldFilesPath,Action<float> _peogress)
	{
		StartCoroutine (download(_newFileIP,_newFilesPath,_oldFilesPath,_peogress));
	}

	IEnumerator download(string _newFileIP, string _newFilesPath,string _oldFilesPath,Action<float> _peogress)
	{
		string newFilesJson;
		string loadNewFileUrl = _newFileIP + "/" + _newFilesPath;
		if(loadNewFileUrl.IndexOf("file:///")==-1 && loadNewFileUrl.IndexOf("http")!=0)
		{
			loadNewF
### 在 Unity 中将 Texture 保存到本地存储 在 Unity 中,可以将 `Texture` 保存为本地文件。通常情况下,这需要创建一个临时的 `Texture2D` 对象来复制原始纹理的内容,然后将其编码为 PNG 或 JPG 格式,并写入到设备的文件系统中[^1]。 以下是实现此功能的完整代码示例: ```csharp using UnityEngine; using System.IO; public class TextureSaver : MonoBehaviour { public Texture texture; // 要保存的 Texture public string savePath = "SavedTexture.png"; // 保存路径和文件名 void SaveTextureToLocalFile(Texture inputTexture, string path) { if (inputTexture == null || !(inputTexture is Texture2D)) { Debug.LogError("输入的 Texture 必须是 Texture2D 类型!"); return; } Texture2D texture2D = inputTexture as Texture2D; // 将 Texture 编码为 PNG 格式 byte[] bytes = texture2D.EncodeToPNG(); // 写入本地文件 File.WriteAllBytes(path, bytes); Debug.Log("Texture 已保存到: " + path); } void OnGUI() { if (GUILayout.Button("保存 Texture")) { if (texture != null) { SaveTextureToLocalFile(texture, Application.dataPath + "/" + savePath); } else { Debug.LogError("请分配一个有效的 Texture!"); } } } } ``` #### 说明 - 上述代码中的 `texture` 必须是一个 `Texture2D` 类型的对象。如果使用的是 `RenderTexture`,则需要先将其内容读取到一个 `Texture2D` 对象中[^2]。 - 使用 `Application.dataPath` 或 `Application.persistentDataPath` 来指定保存路径,以确保文件能够正确保存到设备上[^3]。 - 如果目标平台是移动设备(如 Android 或 iOS),可能需要处理权限问题以访问文件系统[^4]。 通过上述方法,可以将 `Texture` 的内容保存为本地文件。 ---
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值