var a = await Re.Get<T>(name);//T: Texture2D or string
using UnityUtil;
//...
async void Start()
{
Re.basepath=Application.streamingAssetsPath;
//.../Assets/StreamingAssets
//quad
var tex =await Re.Get<Texture2D>("stand.png");
gameObject.GetComponent<Renderer>().material = tex.ToMat();
//rawimage
var tex = await Re.Get<Texture2D>("stand.png");
gameObject.GetComponent<RawImage>().texture = tex;// as Texture;
gameObject.GetComponent<RectTransform>().sizeDelta=new Vector2(tex.width,tex.height);
//image
var tex = await Re.Get<Texture2D>("stand.png");
gameObject.GetComponent<Image>().sprite = tex.ToSprite();
//text
var str= await Re.Get<string>("test.txt");
Debug.Log(str);
Debug.Log("end");
}
namespace UnityUtil
{
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Threading.Tasks;
public static class Re
{
/*usage
using UnityUtil;
Re.basepath=Application.streamingAssetsPath;
var a =await Re.Get<string>("license.txt");
var b= await Re.Get<Texture2D>("zed1.jpg");
*/
public static Dictionary<string, object> cash = new Dictionary<string, object>();
public static string basepath = ".\\";
public static async Task<T> Get<T>(string name)
{
name = name.Trim();
if (!cash.ContainsKey(name))
{
var o = await Load(name);
cash.Add(name, o);
}
//
return (T)cash[name];
}
static async Task<object> Load(string name)
{
var ret = new System.Object();
var path = Path.Combine(basepath, name);
if (isText(name))
{
var str = File.ReadAllText(path);
ret = str;
}
else
{
var tex = new Texture2D(1, 1);
var bytes = File.ReadAllBytes(path);
tex.LoadImage(bytes);
ret = tex;
}
return ret;
//
bool isText(string name) => name.IndexOf(".txt") != -1;
}
public static Material ToMat(this Texture2D tex,string shadername="Transparent/Diffuse"){
Material mat = new Material(Shader.Find(shadername));
mat.SetTexture("_MainTex", tex);
return mat;
}
public static Sprite ToSprite(this Texture2D tex)
{
return Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), Vector2.zero);
}
}
}//namespace