unity读取Android本地图片
一、安卓读取路径
安卓路径:“file:///storage/emulated/0/”+自己图片的路径
例:“file:///storage/emulated/0/small.jpg”
二、unity搭建
使用UI简单搭个界面
三、新建一个脚本
代码内容如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using UnityEngine.Android;public class Test : MonoBehaviour
{string url;public InputField input;public Button btn;public RawImage im;void Start(){
#if UNITY_ANDROID//安卓平台要请求从外部设备读写权限,如果安装后通过了权限请求,则以后这个APP就不会弹出请求权限框//但若安装后请求多次权限,都不通过,则多次后就不会弹出请求权限框//请求从 (SD 卡等)外部存储读取的权限if (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead)){Permission.RequestUserPermission(Permission.ExternalStorageRead);}//请求 写入外部存储(如 SD 卡)的权限 if (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite)){Permission.RequestUserPermission(Permission.ExternalStorageWrite);}
#endifbtn.onClick.AddListener(BtnOnClick);url = "file:///storage/emulated/0/small.jpg";}public void BtnOnClick(){url = input.text;StartCoroutine(getMap());}IEnumerator getMap(){UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(url);yield return webRequest.SendWebRequest();//等待请求完成while (!webRequest.isDone){yield return null;}if (string.IsNullOrEmpty(webRequest.error)){Texture2D texture2D = DownloadHandlerTexture.GetContent(webRequest);if (texture2D){im.texture = texture2D;}}else{Debug.Log("失败");}}
}
四、手机根目录下放一张small.jpg图片
五、打开程序
点击Button按钮读取,读取成功显示图片