Unity讀取Android SDcard文件
阿新 • • 發佈:2017-09-14
tro 如果 studio length == man 兩種 設置 長度
一、添加權限
權限添加 :Player settings -- Other settings -- write permission的設置 Sdcard。這個是在Unity編輯器裏打包的情況。
如果導出到studio 裏面的話,可自行修改Manifest文件。
二、兩種方式
IO方式 加載sdcard上的圖片資源
加載的 /storage/emulated/0/ProjectName/image.jpg,
image = this.GetComponentInChildren<Image>(); Debug.Log("IO加載用時: image = this.GetComponent<Image> ========== " + image); Debug.Log("IO加載: Application.dataPath " + Application.dataPath ); // Application.dataPath /data/app/com.putao.ptx.core-1/base.apk Debug.Log("IO加載: Application.persistentDataPath " + Application.persistentDataPath); // Application.persistentDataPath /storage/emulated/0/Android/data/com.putao.ptx.core/files Debug.Log("IO加載:GameObject.Find" + GameObject.Find("Canvas/Avator").GetComponent<Image>()); // /data/user/0/com.putao.paichallenge/cache/20170524_130527.jpg // path ======= "/storage/emulated/0/ProjectName/image.jpg" FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read); fileStream.Seek(0, SeekOrigin.Begin); //創建文件長度緩沖區 byte[] bytes = new byte[fileStream.Length]; //讀取文件 fileStream.Read(bytes, 0, (int)fileStream.Length); //釋放文件讀取流 fileStream.Close(); fileStream.Dispose(); fileStream = null; //創建Texture int width = 300; int height = 372; Texture2D texture = new Texture2D(width, height); texture.LoadImage(bytes); //創建Sprite Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width,texture.height), new Vector2(0.5f, 0.5f)); image.sprite = sprite;
log上可以看出來 android上 getExternalFilesDir("") 和 Unity裏面的Application.persistentDataPath是一致的
/storage/emulated/0/Android/data/com.putao.ptx.core/filesWWW方式加載本地圖片
url= "file://"+ "/storage/emulated/0/ProjectName/image.jpg"
根本不是加"jar:file://..."
public void LoadByWWW(String path) { StartCoroutine(doLoadByWWW(path)); } IEnumerator doLoadByWWW(String path) { string url = "file://" + "/storage/emulated/0/PaiChallenge/image.jpg"; Debug.Log("doLoadByWWW == url ================== " + url); WWW w = new WWW(url); yield return w; if (w.isDone) { Sprite sprite = Sprite.Create(w.texture, new Rect(0, 0, w.texture.width, w.texture.height), new Vector2(0.5f, 0.5f)); GameObject.Find("Canvas/Avator").GetComponent<Image>().sprite = sprite; }
Unity讀取Android SDcard文件