LoginSignup
8
4

More than 5 years have passed since last update.

UnityWebGLでダウンロードしたファイルを保存して読み込む

Last updated at Posted at 2018-07-30

環境

  • Unity2018.2.0f2
  • WebGL
  • Firefox61.0.1(x64)
  • XAMPP

注意

WebGL のブラウザ間での互換性

Application.persistentDataPathの参照先がIndexedDBから始まるハッシュアドレスになっていたので、未検証ですが上記ページにある表で対応していないブラウザorブラウザバージョンだと動作しない可能性があります。

結論

WebRequestでjson取ってきてApplication.persistentDataPathに保存。
保存したjson読み込むだけ。

普通に他プラットフォームと同じ感じでできる模様。

  • キモとしては以下の二点。
    1. WebGLでもクライアントブラウザ()側でApplication.persistentDataPathが指定できるところ。
    2. ただしファイルとして保存されるのではなくIndexedDBとして保存される。

使い勝手としてはAndroidビルドのUnityの中でFileIO使うのとあんま変わらないんじゃなかろうか。

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

public class WebGLFileIOTest : MonoBehaviour {
    IEnumerator Start()
    {
        UnityWebRequest www = UnityWebRequest.Get("http://localhost/resources/test.json");
        yield return www.SendWebRequest();

        if(www.isNetworkError || www.isHttpError) {
            Debug.Log(www.error);
            yield break;
        }

        string dataPath = Application.persistentDataPath + "/test.json";
        File.WriteAllBytes(dataPath, www.downloadHandler.data);
        string fileData = File.ReadAllText(dataPath);
        Debug.Log(fileData);
    }
}

CORSで弾かれる場合

ただ気を付けないといけないのはCORSによってjsonへのアクセスが弾かれるので、その場合は.htaccessを設定してあげましょう。
↓とりあえず仮サンプル。

localhost/resources/.htaccess
<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Credentials "true"
    Header set Access-Control-Allow-Headers "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time"
    Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
</IfModule>

結果

できた。

localhost/resources/test.json
{"hoge":"fuga"}

WS000083.JPG

8
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4