|
一、使用File读取
void LocalBtyeToImage(Image image, string url) { if (!File.Exists(url)) return; byte[] readBtye = File.ReadAllBytes(url); int width = Screen.width; int height = Screen.height; Texture2D texture = new Texture2D(width, height); texture.LoadImage(readBtye); Sprite sprite = Sprite.Create(texture, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f)); image.sprite = sprite; }二、使用UnityWebRequest获取
IEnumerator FetchLocalPicture(Image image, string url) { if (!File.Exists(url)) yield break; var uri = new System.Uri(Path.Combine(url)); using (UnityWebRequest uwr = UnityWebRequest.Get(uri)) { DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture(true); uwr.downloadHandler = downloadHandlerTexture; yield return uwr.SendWebRequest(); if (uwr.result == UnityWebRequest.Result.Success) { int width = Screen.width; int height = Screen.height; Texture2D texture = new Texture2D(width, height); texture = downloadHandlerTexture.texture; Sprite sprite = Sprite.Create(texture, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f)); image.sprite = sprite; Resources.UnloadUnusedAssets(); } } } |
|