入口业务
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class AbManager : MonoBehaviour
{
private void Awake()
{
DontDestroyOnLoad(gameObject);
}
void Start()
{
List<string> assets_bundle_keys = new List<string>();
if (assets_bundle_keys != null)
{
//填写需要加载的包,要带上后缀名assetbundle或unity3d
assets_bundle_keys.Add("prefabs.assetbundle");
assets_bundle_keys.Add("threeD.unity3d");
}
AssetPack.instance.loadAssetBundle(assets_bundle_keys, onLoadedScenes);
}
void onLoadedScenes()
{
SceneManager.sceneLoaded += OnSceneLoaded;
//包加载完后跳转场景
SceneManager.LoadScene("threeD");
}
public void OnSceneLoaded(Scene scene, LoadSceneMode _mode)
{
SceneManager.sceneLoaded -= OnSceneLoaded;
AssetPack.instance.unLoadAssetBundle("threeD");
//这里可以为场景中添加UI资源
}
}
(ab包加载工具类)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using UnityEngine.Networking;
public class AssetPack : MonoBehaviour
{
public static AssetPack instance;
protected Dictionary<string, object> m_bundles = new Dictionary<string, object>();
string _uri = Application.streamingAssetsPath;
public Text loadingText;
public Text progressText;
public int prograss;
private void Awake()
{
instance = this;
}
//加载指定的ab包
public void loadAssetBundle(List<string> _keys, UnityAction ua)
{
StartCoroutine(loadAb(_keys, ua));
}
//卸载指定的ab包
public void unLoadAssetBundle(string abName)
{
if (m_bundles.ContainsKey(abName))
{
AssetBundle ab = m_bundles[abName] as AssetBundle;
if (ab != null)
{
ab.Unload(false);
}
m_bundles.Remove(abName);
return;
}
}
IEnumerator loadAb(List<string> _keys, UnityAction ua)
{
foreach (var it in _keys)
{
print(_uri);
UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(_uri + "/" + it);
//request.Send();
request.SendWebRequest();
while (!request.isDone)
{
loadingText.text = "正在加载\"" + it + "\"资源包";
prograss = (int)(request.downloadProgress * 100);
progressText.text = prograss + "";
yield return 1;
}
if (request.isDone)
{
prograss = (int)(request.downloadProgress * 100);
loadingText.text = "加载完成\"" + it + "\"资源包";
progressText.text = prograss + "";
AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
m_bundles.Add(it, ab);
}
}
if (ua != null)
{
ua.Invoke();
}
}
//加载ab包中某个资源到对应的场景
public GameObject loadAssetToScene(string abName,string assetName)
{
GameObject obj=null;
if (m_bundles.ContainsKey(abName))
{
AssetBundle ab = m_bundles[abName] as AssetBundle;
if (ab != null)
{
obj = Instantiate(ab.LoadAsset<GameObject>(assetName));
}
}
return obj;
}
}
//下面获取ab包加载的一些根路径
public string getAssetsBundlePath()
{
string assets_path =
#if UNITY_STANDALONE_WIN || UNITY_EDITOR
Application.dataPath + "/StreamingAssets/";
#elif UNITY_ANDROID
"jar:file://" + Application.dataPath + "!/assets/";
#elif UNITY_IPHONE
Application.dataPath + "/Raw/";
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
"file://" + Application.dataPath + "/StreamingAssets/";
#else
Application.dataPath + "/StreamingAssets/";
#endif
return assets_path;
}
第二个场景中实例化一些资源
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class threeD : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
AssetPack.instance.loadAssetToScene("prefabs", "fenshan");
}
// Update is called once per frame
void Update()
{
}
}
准备两个场景
入口场景
下面是跳转的场景
最后打包后运行如下:
备注:上面风扇 发布webgl后 在浏览器上浏览是正常的
打ab包可以用unity自带的AssetBundleBrowser
首次用AssetBundleBrowser,需要在包管理器添加
也可以使用自己写的脚本
打包预设体:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
public class BuildPrefabBundle : MonoBehaviour
{
#region
/*
[MenuItem("AssetBundle/Create AssetBunldes Main")]
static void CreateAssetBundleMain()
{
//获取在Project视图中选择的所有游戏对象
Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
//遍历所有的游戏对象
foreach (Object obj in SelectedAsset)
{
//string sourcePath = AssetDatabase.GetAssetPath(obj);
//本地测试:建议最后将Assetbundle放在StreamingAssets文件夹下,如果没有就创建一个,因为移动平台下只能读取这个路径
//StreamingAssets是只读路径,不能写入
//服务器下载:就不需要放在这里,服务器上客户端用www类进行下载。
string targetPath = Application.dataPath + "/StreamingAssets/" + obj.name + ".assetbundle";
if (BuildPipeline.BuildAssetBundle(obj, null, targetPath, BuildAssetBundleOptions.CollectDependencies, EditorUserBuildSettings.activeBuildTarget))
{
Debug.Log(obj.name + "资源打包成功");
}
else
{
Debug.Log(obj.name + "资源打包失败");
}
}
//刷新编辑器
AssetDatabase.Refresh();
}
*/
#endregion
[MenuItem("Assets/AssetBundle/Create Prefab Bunlde")]
[System.Obsolete]
static void CreateAssetBunldesALL()
{
Caching.ClearCache();
string Path = Application.dataPath + "/StreamingAssets";
Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
//
List<AssetBundleBuild> builds = new List<AssetBundleBuild>();
AssetBundleBuild build = new AssetBundleBuild();
//
List<string> prefab_names = new List<string>();
//
foreach (Object obj in SelectedAsset)
{
if (obj.GetType() == typeof(DefaultAsset))
{
build.assetBundleName = obj.name + ".assetbundle";
}
else
{
prefab_names.Add(AssetDatabase.GetAssetPath(obj));
}
}
build.assetNames = prefab_names.ToArray();
builds.Add(build);
Debug.Log(builds.ToArray());
if (BuildPipeline.BuildAssetBundles(Path, builds.ToArray(), BuildAssetBundleOptions.CollectDependencies, EditorUserBuildSettings.activeBuildTarget))
{
if (File.Exists(Path + "/StreamingAssets"))
{
File.Delete(Path + "/StreamingAssets");
File.Delete(Path + "/StreamingAssets.manifest");
}
string file_name = string.Format("{0}.manifest", build.assetBundleName);
if (File.Exists(Path + "/" + file_name))
{
File.Delete(Path + "/" + file_name);
}
AssetDatabase.Refresh();
}
}
}
打包场景
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.Build.Reporting;
public class BuildSceneBundle : MonoBehaviour
{
//
[MenuItem("Assets/AssetBundle/Create SceneBunlde")]
static void CreateAssetBunldesALL()
{
Caching.ClearCache();
//
Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
//遍历所有的游戏对象
foreach (Object obj in SelectedAsset)
{
string name = AssetDatabase.GetAssetPath(obj);
string [] names = name.Split( new[] { '.', '/' } );
//
BuildReport report = BuildPipeline.BuildPlayer(new[] { name }, Application.dataPath + "/StreamingAssets/" + names[names.Length - 2]+ ".unity3d", EditorUserBuildSettings.activeBuildTarget, BuildOptions.BuildAdditionalStreamedScenes );
BuildSummary summary = report.summary;
if (summary.result == BuildResult.Succeeded)
{
Debug.Log("Build succeeded : " + summary.totalSize + " bytes");
}
//
if (summary.result == BuildResult.Failed)
{
Debug.Log("Build failed !");
}
}
//
AssetDatabase.Refresh();
}
}
FR:徐海涛(hunk Xu)
QQ技术交流群:386476712