示例
#if UNITY_EDITOR
using UnityEditor.SceneManagement;
using UnityEditor;
#endif
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
public enum LoadMode
{
Editor,
Local,
Internet
}
public class LoadAB : MonoBehaviour
{
public LoadMode mode;
void Start()
{
switch (mode)
{
case LoadMode.Editor:
#if UNITY_EDITOR
EditorLoadAbContent();
#endif
break;
case LoadMode.Local:
LocalLoad();
break;
case LoadMode.Internet:
StartCoroutine(InternetLoad(Application.dataPath + "/../AssetBundles/prefabs"));
break;
}
}
}
编辑器中加载ab包内容
#if UNITY_EDITOR
void EditorLoadAbContent()
{
var levels = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName("scene", "New Scene");
if (levels.Length > 0)
{
var loadParamters = new LoadSceneParameters(LoadSceneMode.Single);
var operation = EditorSceneManager.LoadSceneAsyncInPlayMode(levels[0], loadParamters);
operation.completed += (value) =>
{
var assets = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName("prefabs", "Cube");
if (assets.Length > 0)
{
Object target = AssetDatabase.LoadMainAssetAtPath(assets[0]);
if (target)
{
Instantiate(target);
}
}
};
}
}
#endif
本地加载ab包
void LocalLoad()
{
var mainBundle = AssetBundle.LoadFromFile(Application.dataPath + "/../AssetBundles/AssetBundles");
AssetBundleManifest abMainfest = mainBundle.LoadAsset<AssetBundleManifest>("assetbundlemanifest");
var strs = abMainfest.GetAllDependencies("prefabs");
for (int i = 0; i < strs.Length; i++)
{
AssetBundle.LoadFromFile(Application.dataPath + "/../AssetBundles/" + strs[i]);
}
var parfabs2 = AssetBundle.LoadFromFile(Application.dataPath + "/../AssetBundles/prefabs");
var obj = parfabs2.LoadAsset<GameObject>("Cube");
Instantiate(obj);
}
远程加载ab包
IEnumerator InternetLoad(string abPath)
{
UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(abPath);
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
if (bundle != null)
Debug.Log("远程加载ab包成功");
}
else
Debug.Log("错误信息 " + request.error);
}