LoginSignup
0
0

More than 3 years have passed since last update.

StreamingAssetsに置いた圧縮済みテキストをロードする (unity)

Last updated at Posted at 2019-07-05

前提

  • unity 2018.4.3f1

やりたいこと

  • StreamingAssetsにgzip圧縮したテキストファイル(.txt.gz)を入れておき、ランタイムに読み出して使いたい。

コード

using System.IO;
using System.IO.Compression;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

public class SampleMain : MonoBehaviour {

    void Start () {
        Debug.Log ("sample.txt.gz".LoadStremingText () ?? "Error");
    }

}

public static class Sample {

    public static string LoadStremingText (this string filename) {
        string sourcePath = Path.Combine (Application.streamingAssetsPath, filename);
        var gz = filename.EndsWith (".gz");
        if (sourcePath.Contains ("://")) { // Android
            using (var www = UnityWebRequest.Get (gz ? sourcePath.Substring (0, sourcePath.Length - 3) : sourcePath)) {
                www.SendWebRequest ();
                while (!www.isDone && !www.isNetworkError && !www.isHttpError) { }
                if (!www.isNetworkError && !www.isHttpError) {
                    return www.downloadHandler.text;
                }
            }
        } else if (File.Exists (sourcePath)) { // Mac, Windows, iPhone
            if (gz) {
                using (var data = File.OpenRead (sourcePath))
                using (var compresed = new GZipStream (data, CompressionMode.Decompress))
                using (var text = new MemoryStream ()) {
                    compresed.CopyTo (text);
                    return Encoding.UTF8.GetString (text.ToArray ());
                }
            } else {
                return File.ReadAllText (sourcePath);
            }
        }
        return null;
    }

}

留意点

修正

  • 2020/04/04
    • iOSでアクセス権違反が生じるため、new FileStream (sourcePath, FileMode.Open)File.OpenRead (sourcePath)に置き換えました。
0
0
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
0
0