AssetBundleHelper
2016-09-02 本文已影响207人
2b75747cf703
using UnityEngine;
using System.Collections;
using System;
namespace Babybus.Framework.Extension
{
public class AssetBundleHelper : MonoBehaviour
{
private static AssetBundleHelper instance;
private static AssetBundleHelper Instance
{
get
{
if (instance == null)
{
GameObject go = new GameObject("AssetBundleHelper");
instance = go.AddComponent<AssetBundleHelper>();
DontDestroyOnLoad(go);
}
return instance;
}
}
public static AssetBundle LoadFromResources(string path)
{
var textAsset = Resources.Load<TextAsset>(path);
if (textAsset == null)
return null;
return LoadFromMemory(textAsset.bytes);
}
public static void LoadFromResourcesAsync(string path, Action<AssetBundle> action)
{
Instance.StartCoroutine(LoadFromResourcesCoroutine(path, action));
}
private static IEnumerator LoadFromResourcesCoroutine(string path, Action<AssetBundle> action)
{
var request = Resources.LoadAsync<TextAsset>(path);
yield return request;
if (action == null)
yield break;
if (request == null || request.asset == null)
action(null);
else
LoadFromMemoryAsync((request.asset as TextAsset).bytes, action);
}
public static void LoadFromStreamingAssets(string name, Action<AssetBundle> action)
{
LoadFromWWW("file:///" + Application.streamingAssetsPath + name, action);
}
public static void LoadFromWWW(string url, Action<AssetBundle> action)
{
Instance.StartCoroutine(LoadFromWWWCoroutine(url, action));
}
private static IEnumerator LoadFromWWWCoroutine(string url, Action<AssetBundle> action)
{
WWW www = new WWW(url);
yield return www;
if (action != null)
action(www == null ? null : www.assetBundle);
}
public static AssetBundle LoadFromFile(string path)
{
return AssetBundle.LoadFromFile(path);
}
public static void LoadFromFileAsync(string path, Action<AssetBundle> action)
{
Instance.StartCoroutine(LoadFromFileAsyncCoroutine(path, action));
}
private static IEnumerator LoadFromFileAsyncCoroutine(string path, Action<AssetBundle> action)
{
var request = AssetBundle.LoadFromFileAsync(path);
yield return request;
if (action != null)
action(request == null ? null : request.assetBundle);
}
public static AssetBundle LoadFromMemory(byte[] binary)
{
return AssetBundle.LoadFromMemory(binary);
}
public static void LoadFromMemoryAsync(byte[] binary, Action<AssetBundle> action)
{
Instance.StartCoroutine(LoadFromMemoryAsyncCoroutine(binary, action));
}
private static IEnumerator LoadFromMemoryAsyncCoroutine(byte[] binary, Action<AssetBundle> action)
{
var request = AssetBundle.LoadFromMemoryAsync(binary);
yield return request;
if (action != null)
action(request == null ? null : request.assetBundle);
}
}
}