Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Collections;
using System.IO;
using Unity.Networking;
using UnityEngine;
using UnityEngine.UI;
public class DownloadAndDisplay : MonoBehaviour
{
[SerializeField]
private string downloadFileURL = "https://user-images.githubusercontent.com/1644563/50053779-1b7a0780-017e-11e9-9736-d88ec4773704.png";
const string saveFilePath = "image.png";
// ファイルの格納先はApplication.persistentDataPathを基準とした相対パスなので、プロパティ作っとく
string FilePath { get { return Path.Combine(Application.persistentDataPath, saveFilePath); } }
Texture2D texture;
private void Awake()
{
texture = new Texture2D(2, 2);
}
private void OnDestroy()
{
Destroy(texture);
}
public void RemoveFile()
{
if (File.Exists(FilePath))
File.Delete(FilePath);
}
public void DownloadStart()
{
StartCoroutine(DownloadFileTest());
}
IEnumerator DownloadFileTest()
{
BackgroundDownloadConfig config = new BackgroundDownloadConfig
{
filePath = saveFilePath,
url = new Uri(downloadFileURL),
policy = BackgroundDownloadPolicy.Default
};
// AndroidのPermissionでエラーが出る事があるので、BackgroundDownload.Startはtry-catchで囲いたいけど、
// 開放漏れのほうが怖いのでusingで囲う
using (var download = BackgroundDownload.Start(config))
{
yield return download;
Debug.Log(download.status);
}
// ダウンロード完了後に即座に処理を始めるとUI等が更新されず最後の状態で長時間待つ事になる
// 事後処理(Zip解答等)があるなら、このタイミングで一旦画面を更新しとくのが良さそう
yield return null;
// ダウンロード失敗や諸々の要因で読取り失敗するので、try-catchで囲っとく
try
{
var data = File.ReadAllBytes(FilePath);
texture.LoadImage(data, false);
GetComponent<RawImage>().texture = texture;
}
catch (IOException e) { Debug.LogError(e); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.