Unityでダウンロードしたファイルの永続化と読み込み
ダウンロードしたリソース(csvファイル)をローカルに保存する&保存したリソースを読み込むサンプル
ダウンロード&永続化
using UnityEngine;
using System.Collections;
using System.IO;
public class WWWLoader : MonoBehaviour {
IEnumerator Start () {
WWW www = new WWW("http://127.0.0.1:8000/static/sample.csv");
while (!www.isDone) { // ダウンロードの進捗を表示
print(Mathf.CeilToInt(www.progress*100));
yield return null;
}
if (!string.IsNullOrEmpty(www.error)) { // ダウンロードでエラーが発生した
print(www.error);
} else { // ダウンロードが正常に完了した
File.WriteAllBytes(Application.persistentDataPath + "/" + Path.GetFileName(www.url), www.bytes);
}
}
}
読み込み(WWWクラスを使う)
using UnityEngine;
using System.Collections;
public class FileLoader : MonoBehaviour {
IEnumerator Start () {
WWW www = new WWW("file://" + Application.persistentDataPath + "/sample.csv");
while (!www.isDone) { // 読み込みの進捗を表示
print(Mathf.CeilToInt(www.progress*100));
yield return null;
}
if (!string.IsNullOrEmpty(www.error)) { // 読み込みでエラーが発生した
print(www.error);
} else { // 読み込みが正常に完了した
print(www.text);
}
}
}
読み込み(Fileクラスを使う)
using UnityEngine;
using System.Collections;
using System.IO;
public class FileLoader2 : MonoBehaviour {
void Start () {
string text = File.ReadAllText(Application.persistentDataPath + "/sample.csv");print(text);
}
}
補足
- Fileクラスのメソッドは例外をcatchすべきかもしれません
(例えば存在しないファイルをFile.ReadAllTextした場合はFileNotFoundException
が発生する) - 大容量なファイルをFileクラスで入出力する場合は非同期な工夫が必要かもしれません