资源加载
方式一:使用全局变量,以拖动的方式赋值
public class Main : MonoBehaviour
{
public TextAsset indexJson;
...
方式二:新建Resources文件夹
把资源文件放在该文件夹下,例如index.json这个文件,加载的时候只需要写成index,不需要带着后缀名。 Resources文件夹可以位于Assets文件夹的任意位置。
var x = Resources.Load<TextAsset>("index");
Debug.Log($"resource .length={x.text.Length}");
方式三:网络加载资源
var t = await Util.GetRemoteTexture("https://forum.unity.com/data/avatars/m/628/628421.jpg?1441745369");
var obj = new GameObject();
obj.AddComponent<RawImage>();
var rawImage = obj.GetComponent<RawImage>();
rawImage.texture = t;
使用网络请求获取资源
public static async Task<Texture2D> GetRemoteTexture(string url)
{
using (UnityWebRequest req = UnityWebRequestTexture.GetTexture(url))
{
req.certificateHandler = new BypassCertificate();
// begin request:
var asyncOp = req.SendWebRequest();
// await until it's done:
while (asyncOp.isDone == false)
await Task.Delay(1000 / 30); //30 hertz
// read results:
if (req.result == UnityWebRequest.Result.ConnectionError || req.result == UnityWebRequest.Result.ProtocolError)
{
Debug.Log($"{req.error}, URL:{req.url}");
return null;
}
else
{
// return valid results:
return DownloadHandlerTexture.GetContent(req);
}
}
}
方式四:通过AssetDatabases加载资源
{
//使用AssetDatabase加载图片,图片的位置可以比较随意
var x = AssetDatabase.FindAssets("PICODeveloper");
Debug.Log($"assets:{string.Join(",", x)}");
if (x.Length > 0)
{
var assetId = x[0];
var filepath = AssetDatabase.GUIDToAssetPath(assetId);
texture = AssetDatabase.LoadAssetAtPath<Texture>(filepath);
}
}