用AB包加载场景

场景构建AB包的方法和资源类似:从AB中加载场景是不用把场景放到scene in Build中的,加载后读取即可。

using UnityEngine;
using System.IO;
using UnityEngine.Events;
using UnityEditor;
using System.Collections.Generic;


public class BuildAB  
{
	[MenuItem("Tools/BuildAssetbundle")]
	static void BuildAssetbundle()
	{
		string outPath = Path.Combine (Application.dataPath, "StreamingAssets");

		//如果目录已经存在删除它
		if (Directory.Exists (outPath)) {
			Directory.Delete (outPath,true);
		}
		Directory.CreateDirectory (outPath);

		List<AssetBundleBuild> builds = new List<AssetBundleBuild> ();
		//设置bundle名,和多少资源打在同一个Bundle内
		builds.Add (new AssetBundleBuild (){assetBundleName="scene-ab.unity3d",assetNames =new string[]{"Assets/scene-ab.unity"}});

		//构建Assetbundle
		BuildPipeline.BuildAssetBundles (outPath,builds.ToArray(),BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.DeterministicAssetBundle, BuildTarget.StandaloneWindows64);
		//刷新
		AssetDatabase.Refresh ();
	}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.SceneManagement;

public class LoadABScene : MonoBehaviour {

	void Start () {
		string path = Path.Combine (Application.streamingAssetsPath, "scene-ab.unity3d");
		//加载场景Bundle
		AssetBundle.LoadFromFile (path);
		SceneManager.LoadScene ("scene-ab");
	}
}

 

Unity 加载场景AB通常是指将复杂的项目分解成多个小规模的场景(也称为“”或“Asset Bundle”),以便于管理、优化资源加载速度以及分发。AB是一种在运行时动态加载的内容形式,特别是在需要根据用户需求或网络条件加载额外内容的情况下。 要在Unity中加载AB,你可以按照以下步骤操作: 1. 创建或导入场景:首先,将需要的部分场景分别保存为单独的AB文件。每个AB含一组相关的游戏物体、纹理、音频等资源。 2. 编写脚本:在主场景或者游戏内的某个地方编写C#脚本,例如`WWW`或`UnityWebRequest`,用于异步下载并解压缩AB。 ```csharp using UnityEngine; using System.Collections.Generic; using UnityEngine.UI; public class LoadSceneBundle : MonoBehaviour { public string bundleURL; // AB的URL public GameObject container; // 要添加到的游戏对象容器 private async void Start() { WWW www = new WWW(bundleURL); await www_download(www); } private IEnumerator.www_download(WWW www) { yield return www; if (www.isDone && !www.error) { byte[] data = www.bytes; List<UnityEngine.Object> importedObjects = AssetDatabase.ImportPackageFromMemory(data, "Temp"); foreach (UnityEngine.Object obj in importedObjects) { container.AddComponent(obj); } } else { Debug.LogError("Failed to load scene bundle: " + www.error); } } } ``` 3. 设置场景切换:当AB下载并成功导入后,你可以将其中的游戏对象添加到目标容器或直接设置为当前活动场景
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值