Help us understand the problem. What is going on with this article?

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

前提

  • 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 = new FileStream (sourcePath, FileMode.Open))
                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;
    }

}

留意点

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away