【Unity】サーバーからローカルに画像を落として利用する方法
プロジェクトの中にリソースを含めたくないとか、データの更新するために外部化したいみたいなときに
画像データをダウンロードして利用すると便利です
Unityでは【Application.persistentDataPath】で開かれるディレクトリに保存することで利用可能です
Windowsで開発しているならば、実際にデータを放り込んでダウンロード後の扱いについても簡単にチェック出来ます
下のソースはサーバーからダウンロードして、ローカルに保存する処理です。
StartCoroutineを使って呼び出せば簡単にダウうロードすることが出来ます。
_strUrl :サーバーへのURL
_strLocalPath :ローカルパス。相対位置の調整したいときなどに利用
_strFilename :実際のファイル名。拡張子服務
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
IEnumerator download (string _strUrl , string _strLocalPath , string _strFilename ) { string server_file_path = System.IO.Path.Combine (_strUrl, _strLocalPath); server_file_path = System.IO.Path.Combine (server_file_path, _strFilename); if (_strLocalPath.Equals ("") == false ) { server_file_path = string.Format ("{0}/{1}/{2}", _strUrl,_strLocalPath, _strFilename); } else { server_file_path = string.Format ("{0}/{1}", _strUrl, _strFilename); } string persisten_file_path = System.IO.Path.Combine (Application.persistentDataPath, _strLocalPath); persisten_file_path = System.IO.Path.Combine (persisten_file_path, _strFilename); Debug.Log (server_file_path); WWW www = new WWW (server_file_path); yield return www; if (www.error == null) { File.WriteAllBytes (persisten_file_path, www.bytes); } else { Debug.LogError (www.error); } m_bLoadEnd = true; yield return 0; } |
サンプルコードの中にあるm_bLoadEndはクラスのメンバー変数で、ロード完了通知として利用してます。
(イベント投げるように設定してあればそちらの方がいいかも知れません。)
また、ファイルのアクセスはたまに例外も投げられるので、try-catchで囲んでおくと安心!
ちなみに私はテキスト系や画像は生データ、サウンドファイルはアセットバンドル、という感じで使い分けてます。
いろいろ試してみましたがサウンドファイルはそのままでは扱えないっぽくて、アセットバンドル経由でしかうまく鳴らせませんでした。
だれか偉い人教えて!!