Cocos Creator资源热更新实战:基于Manifest的版本控制
你是否还在为游戏发布后无法更新资源而烦恼?用户反馈资源加载缓慢、新内容无法及时上线?本文将通过Cocos Creator的Manifest机制,带你一步实现资源热更新功能,解决版本控制难题。读完本文你将掌握:Manifest文件结构解析、热更新流程实现、版本对比算法及异常处理方案。
热更新核心原理
热更新(Hot Update)是指应用在不重新安装的情况下,动态下载并更新资源文件的技术。Cocos Creator通过Manifest文件实现版本控制,其核心原理是:
- 客户端维护本地Manifest清单
- 与服务器Manifest对比差异资源
- 下载差异资源并更新本地版本
技术要点:Cocos Creator的热更新模块主要实现在exports/asset-manager.ts中,通过AssetManager类管理资源加载与版本控制。
Manifest文件结构
Manifest文件是热更新的核心,采用JSON格式存储资源版本信息。典型的Manifest结构如下:
{
"packageUrl": "http://example.com/update/",
"remoteManifestUrl": "http://example.com/update/project.manifest",
"remoteVersionUrl": "http://example.com/update/version.manifest",
"version": "1.0.1",
"assets": {
"res/background.jpg": {
"size": 102400,
"md5": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6"
},
"src/game.js": {
"size": 20480,
"md5": "f1e2d3c4b5a6f7e8d9c0b1a2f3e4d5c6"
}
},
"searchPaths": []
}
| 字段 | 说明 |
|---|---|
| packageUrl | 远程资源根目录 |
| remoteManifestUrl | 远程Manifest文件URL |
| remoteVersionUrl | 远程版本文件URL |
| version | 当前版本号 |
| assets | 资源列表(包含size和md5) |
| searchPaths | 资源搜索路径 |
实现参考:Manifest文件的解析逻辑可查看cocos/asset-manager/manifest.ts,其中定义了Manifest类及版本对比方法。
热更新实现步骤
1. 配置热更新模块
首先需要在项目中初始化热更新模块,设置远程服务器地址和本地存储路径:
import { assetManager } from 'cc';
import { Manifest } from 'cc/asset-manager';
// 初始化热更新
const hotUpdateUrl = 'http://example.com/update/';
const storagePath = assetManager.utils.getWritablePath() + '/hotupdate';
// 创建Manifest实例
const manifest = new Manifest({
packageUrl: hotUpdateUrl,
remoteManifestUrl: hotUpdateUrl + 'project.manifest',
remoteVersionUrl: hotUpdateUrl + 'version.manifest'
}, storagePath);
2. 版本检查与对比
通过对比本地与远程Manifest的version字段,判断是否需要更新:
// 检查版本差异
assetManager.hotUpdate.checkUpdate(manifest, (err, hasUpdate) => {
if (err) {
console.error('版本检查失败:', err);
return;
}
if (hasUpdate) {
console.log('发现新版本,开始更新');
// 执行更新
startUpdate(manifest);
} else {
console.log('当前已是最新版本');
}
});
关键算法:版本对比逻辑实现在src/marionette/version-compare.ts中,采用语义化版本比较算法。
3. 资源下载与更新
下载差异资源并更新本地Manifest:
function startUpdate(manifest) {
const updateListener = {
onProgress: (completed, total) => {
const progress = (completed / total) * 100;
console.log(`更新进度: ${progress.toFixed(1)}%`);
// 更新UI进度条
},
onSuccess: () => {
console.log('更新成功,重启应用');
// 重启游戏使更新生效
assetManager.hotUpdate.loadNewManifest(manifest);
cc.game.restart();
},
onFail: (err) => {
console.error('更新失败:', err);
}
};
// 开始下载更新
assetManager.hotUpdate.update(manifest, updateListener);
}
高级特性与最佳实践
断点续传实现
Cocos Creator的热更新模块内置断点续传功能,通过pal/network/downloader.ts实现,支持网络中断后继续下载:
// 配置断点续传
assetManager.downloader.setOptions({
retryCount: 3, // 重试次数
timeout: 30000, // 超时时间(ms)
resumeDownload: true // 启用断点续传
});
版本回滚机制
当更新失败时,可通过备份的Manifest文件回滚到上一版本:
// 版本回滚
function rollbackUpdate() {
const backupManifestPath = storagePath + '/project.manifest.bak';
if (fs.existsSync(backupManifestPath)) {
fs.copyFileSync(backupManifestPath, storagePath + '/project.manifest');
console.log('已回滚到上一版本');
cc.game.restart();
}
}
资源校验与完整性检查
通过MD5校验确保资源完整性,实现代码在cocos/asset-manager/cache-manager.ts:
// 验证资源MD5
function verifyAsset(assetPath, expectedMd5) {
const actualMd5 = assetManager.utils.md5File(assetPath);
return actualMd5 === expectedMd5;
}
常见问题解决方案
1. 网络异常处理
// 网络错误重试策略
assetManager.hotUpdate.setRetryConfig({
maxRetryCount: 3,
retryInterval: 2000
});
2. 存储空间不足
// 检查存储空间
function checkStorageSpace(requiredSize) {
const freeSpace = assetManager.utils.getFreeDiskSpace(storagePath);
return freeSpace >= requiredSize;
}
3. Manifest文件损坏
定期备份Manifest文件:
// 备份Manifest
function backupManifest() {
fs.copyFileSync(
storagePath + '/project.manifest',
storagePath + '/project.manifest.bak'
);
}
总结与展望
本文详细介绍了Cocos Creator基于Manifest的资源热更新方案,包括:
- Manifest文件结构与版本控制原理
- 热更新完整实现流程(配置-检查-下载-更新)
- 高级特性(断点续传、版本回滚、完整性校验)
- 常见问题解决方案
随着游戏规模扩大,建议结合docs/contribution/modules.md中的模块化设计理念,将热更新功能封装为独立模块,提高代码复用性。
下期预告:Cocos Creator热更新高级优化:资源分块与增量更新技术
点赞+收藏+关注,获取更多Cocos开发实战技巧!如有疑问欢迎在评论区留言讨论。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考





