Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9543

StreamingAssetsでTextureをロードする方法

$
0
0

はじめに

意外と、これだけのシンプルな内容の記事がなかったので端的に書いてみました。

対象

・unityのC#がわかる
・Resouces使いたくない
・コルーチンがわかる
・Actionがかわる
・WWW使いたくない

本題

using UnityEngine.Networking;

------------------

        private Texture textureTest;
        protected string path;

        public void Start() {
//StreamingAssets内のTestフォルダのAというjpeg画像のパス指定
      SetPath(Test/A.jpg);
           StartCoroutine (DownloadTexture (r => textureTest = r));
        }

//StreamingAssetsフォルダー内のパスの指定
        public void SetPath (string url) {
            path = url;
        }

        public IEnumerator DownloadTexture (Action<Texture> callback) {
//StreamingAssetsまでのパスと内側のパスをつなげる
            var url = System.IO.Path.Combine (Application.streamingAssetsPath, path);
            url = "file://" + url;

            using (UnityWebRequest www = UnityWebRequestTexture.GetTexture (url)) {
                yield return www.SendWebRequest ();
                if (www.isNetworkError || www.isHttpError) {
                    Debug.Log (www.error);
                    yield break;
                }
                var myTexture = ((DownloadHandlerTexture) www.downloadHandler).texture;
//コルーチンは返り値を持てないので、Actionで返す
                callback (myTexture);
            };
        }

解説

SetPath(Test/A.jpg);

この引数の部分を自分のフォルダーに変更してください。

最後に

StreamingAssetsはなんぞや
どういう利点が?
等は他に良記事が多数なのでググってみてください。


Viewing all articles
Browse latest Browse all 9543

Trending Articles