unity三種資源載入方式Resources,AssetBundle,WebRequset的同步非同步載入
阿新 • • 發佈:2021-01-12
using System; using System.Collections; using UnityEngine; using UnityEngine.Networking; public enum AssetLoadMode { Resource, AssetBundle, WebRequest } public class AssetDownLoadComponent : GameComponent { void Awake() { Initinalize(); } public T ResourcesLoad<T>(stringpath) where T : UnityEngine.Object { return Resources.Load<T>(path); } public void ResourcesAsyncLoad<T>(string path, Action<ResourceRequest> action) where T : UnityEngine.Object { StartCoroutine(ResourcesAsync<T>(path,action)); } publicvoid UnityWebRequested(string url, Action<UnityWebRequest> callback) { StartCoroutine(UnityWebRequestLoad(url,callback)); } public T AssetBundleLoad<T>(string path, RuntimePlatform runtimePlatform) where T:UnityEngine.Object { AssetBundle asset= LoadAssetBundle(path, runtimePlatform);string name = path.Substring(path.LastIndexOf('/')); name = name.Substring(0,name.Length-3); return asset.LoadAsset<T>(name); } public void AssetBundleAsyncLoad(string path, Action<AssetBundleCreateRequest> callBack, RuntimePlatform runtimePlatform) { StartCoroutine(AssetBundleLoadAsync(path,callBack, runtimePlatform)); } private IEnumerator ResourcesAsync<T>(string path, Action<ResourceRequest> action) where T : UnityEngine.Object { ResourceRequest resourcesRequest = Resources.LoadAsync<T>(path); yield return resourcesRequest; if (resourcesRequest.asset!=null) { action(resourcesRequest); } else { Debug.LogError(path+"無法載入"); } } private IEnumerator UnityWebRequestLoad(string url, Action<UnityWebRequest> callback) { UnityWebRequest webRequest = UnityWebRequest.Get(url); yield return webRequest.SendWebRequest(); if (webRequest.isNetworkError || webRequest.isHttpError) { Debug.Log(webRequest.error); } else { callback.Invoke(webRequest); } } private AssetBundle LoadAssetBundle(string path, RuntimePlatform runtimePlatform) { string root = System.IO.Path.Combine(Application.streamingAssetsPath, "AssetBundle/Win/"); switch (runtimePlatform) { case RuntimePlatform.Android: root = System.IO.Path.Combine(Application.streamingAssetsPath, "AssetBundle/Android/"); break; default: break; } Uri uri = new Uri(root+path); return AssetBundle.LoadFromFile(uri.AbsolutePath); } private IEnumerator AssetBundleLoadAsync(string path,Action<AssetBundleCreateRequest> callBack,RuntimePlatform runtimePlatform) { string root = System.IO.Path.Combine(Application.streamingAssetsPath, "AssetBundle/Win/"); switch (runtimePlatform) { case RuntimePlatform.Android: root = System.IO.Path.Combine(Application.streamingAssetsPath, "AssetBundle/Android/"); break; default: break; } Uri uri = new Uri(root + path); AssetBundleCreateRequest assetBundleCreateRequest = AssetBundle.LoadFromFileAsync(uri.AbsolutePath); yield return assetBundleCreateRequest; callBack(assetBundleCreateRequest); } }