从 v2.4 开始,Creator 正式支持 Asset Bundle 功能。Asset Bundle 可以按需求随意放置,比如可以放在远程服务器、本地、或者小游戏平台的分包中。也可以跨项目复用,用于加载子项目中的 Asset Bundle。
加载Asset Bundle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| cc.assetManager.loadBundle('bundle1', (err, bundle) => { });
cc.assetManager.loadBundle(jsb.fileUtils.getWritablePath() + '/myBundleName', (err, bundle) => { });
cc.assetManager.loadBundle(wx.env.USER_DATA_PATH + '/pathToBundle/bundleName', (err, bundle) => { });
|
加载 Asset Bundle 中的资源
在 Asset Bundle 加载完成后,返回了一个 cc.AssetManager.Bundle
类的实例。我们可以通过实例上的 load
方法来加载 Asset Bundle 中的资源,此方法的参数与 cc.resources.load
相同,只需要传入资源相对 Asset Bundle 的路径即可。但需要注意的是,路径的结尾处 不能 包含文件扩展名。
- 单独加载
- load() 是通过相对路径加载分包中的资源。路径是相对分包文件夹路径的相对路径
- 携带四个参数
paths
加载文件的路径、type
加载文件的类型如cc.Prefab、onProgress
可选参数、onComplete
回调函数,加载成功或失败时回调
1 2 3 4 5 6
|
bundle.load(`prefab`, cc.Prefab, (err, prefab) => { });
|
- 批量加载
- loadDir() 加载目标文件夹中的所有资源, 注意:路径中只能使用斜杠,反斜杠将停止工作
- 携带四个参数
dir
分包中文件夹名称、type
加载文件的类型如cc.Prefab可选、onProgress
可选参数、onComplete
回调函数,加载成功或失败时回调
1 2 3 4 5 6 7 8 9
| bundle.loadDir("textures", (err, assets) => { });
bundle.loadDir("textures", cc.Texture2D, (err, assets) => { });
|
- 加载bundle中的场景
- loadScene() 通过场景名称加载分包中的场景
- 携带四个参数
sceneName
要加载的场景名称、options
一些可选参数、onProgress
加载进度回调函数(finis已完成的项目数 ,total 项目的总数,item最新的请求项)可选、onComplete
回调函数,将在场景启动后调用
1 2 3 4 5
| bundle.loadScene('test', (err, scene) => { cc.director.runScene(scene); });
|
获取 Asset Bundle
当 Asset Bundle 被加载过之后,会被缓存下来,此时开发者可以使用 Asset Bundle 名称来获取该 bundle
- getBundle() 获取已加载的分包
- 携带一个参数
name
分包名称
1 2 3 4 5 6 7
| let isBundle = cc.assetManager.getBundle('bundle'); if ( isBundle ) { } else { }
|