C# Unity用AssetBundle載入本地資源 (1)
/// AssetBundle載入器
/// </summary>
public class AssetBundleLoger
{
/// <summary>
/// 更新檔案下載目錄
/// </summary>
private const string StreamingAssetPath = "/StreamingAssets/";
private static string _ApplicationStreamingAssets = Application.streamingAssetsPath;
public static string ApplicationDataPath = Application.dataPath;
public static string ApplicationPersistentAssets = Application.platform == RuntimePlatform.Android ? Application.persistentDataPath : _ApplicationStreamingAssets;
/// <summary>
/// assetbundle記憶體列表
/// </summary>
private static Dictionary<string, AssetBundle> AssetBundleArray = new Dictionary<string, AssetBundle>();
/// <summary>
/// object記憶體列表, 用來快取assetbundle加載出的object物件加快載入速度
/// </summary>
private static Dictionary<string, object> _ObjectMemory = new Dictionary<string, object>();
/// <summary>
/// 根據平臺區分路徑間隔
/// </summary>
/// <returns></returns>
public static string GetPathGap()
{
var gapPath = StreamingAssetPath;
if (Application.platform == RuntimePlatform.WindowsEditor)
{
gapPath = "/";
}
return gapPath;
}
/// <summary>
/// 載入AssetBundle(<可能會有載入時間過長的問題, 測試版本>)
/// </summary>
/// <param name="path">assetbundle地址</param>
/// <returns>assetbundle物件</returns>
private static AssetBundle LoadAssetBundle(string path)
{
return AssetBundle.CreateFromFile(path);
}
/// <summary>
/// AssetBundle載入
/// </summary>
/// <param name="path">名字</param>
/// <param name="loadType">載入的型別</param>
/// <returns></returns>
public static Object Load(string path, Type loadType)
{
try
{
// 資源Assetbundle
AssetBundle source = null;
Object result = null;
Stopwatch sw = new Stopwatch();
sw.Start();
if (!AssetBundleArray.ContainsKey(path))
{
var dep = LoadAssetBundle(ApplicationPersistentAssets + GetPathGap() + path + ".assetbundle");
AssetBundleArray.Add(path, dep);
source = dep;
}
else
{
source = AssetBundleArray[path];
}
result = source.Load(path, loadType);
sw.Stop();
Debug.Log("耗時" + sw.ElapsedMilliseconds);
return result;
}
catch (Exception)
{
throw;
}
}