using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
public static class LoadHelper
{
public static async Task<Sprite> LoadSpritePNG(string path)
{
var task = LoadAsyncSprite(path, ".png");
Task<Sprite> t = await Task.WhenAny(task);
return t.Result;
}
public static async Task<Sprite> LoadSpriteJPG(string path)
{
var task = LoadAsyncSprite(path, ".jpg");
Task<Sprite> t = await Task.WhenAny(task);
return t.Result;
}
static async Task<Sprite> LoadAsyncSprite(string url, string end)
{
string path = Path.Combine(Application.streamingAssetsPath, url + end);
var getRequest = UnityWebRequest.Get(path);
await getRequest.SendWebRequest();
byte[] imgData = getRequest.downloadHandler.data;
Texture2D tex = new Texture2D(2, 2);
tex.LoadImage(imgData);
Vector2 pivot = new Vector2(0.5f, 0.5f);
Sprite sprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), pivot, 100.0f);
return sprite;
}
}
public static class ExtensionMethods
{
public static TaskAwaiter GetAwaiter(this AsyncOperation asyncOp)
{
var tcs = new TaskCompletionSource<object>();
asyncOp.completed += obj => { tcs.SetResult(null); };
return ((Task)tcs.Task).GetAwaiter();
}
}
调用
async void Read()
{
Sprite sp = await LoadHelper.LoadSpritePNG(path);
}