实现分两步:
1.远程加载服务器资源,在游戏主循环调用 GameBundleData.Instance.update();
export class GameBundleData extends Singleton {
last_update_time:number = null; // 最后更新时间
public update():void { // 检测更新资源包
CF.delay(()=>{
let con = false;
if(this.last_update_time){
let t = CFTime.timeStamp();
if((t-this.last_update_time)/1000/60 >= 5){
//console.log('【游戏资源包数据】定时5分钟检测更新资源包触发...');
this.last_update_time = t;
con = true;
}
}else{
this.last_update_time = CFTime.timeStamp();
con = true;
}
if(con){
CF.delay(()=>{
this.update_bundle();
},0.001);
}
},0.001);
}
private update_bundle():void { // 更新资源包
//读取服务器配置获取资源包版本信息
//加载资源包
Res.loadBundle('reslib','',(err,bundle)=>{
if(err){
return console.error(err);
}
if(bundle){
Game.Instance._bundle_reslib = bundle;
}
});
}
}
其中 Game.Instance._bundle_reslib 为 Game文件中的全局变量 _bundle_reslib:AssetManager.Bundle = null; // 资源包对象 reslib
2.自己写工具加载模型到游戏里 工具文件名为 Res
public static loadBundle(name:string,version:string,cb?: (err:Error | null, bundle?: AssetManager.Bundle)=>void) {
assetManager.loadBundle(name,{version:version},cb);
}
public static instBundlePrefab3d(bundle: AssetManager.Bundle, root:Node | undefined = undefined, pos:Vec3 = Vec3.ZERO, path: string, cb?: (err:Error | null, asset?: Node)=>void) {
Res.loadBundlePrefab(bundle,path,(err,asset)=>{
if(CF.isNull(asset)){
console.error('通过服务器实例3D模型 - 资源为空 : ',path);
return;
}
cb(err,Res.inst3d(asset,root,pos));
});
}
public static loadBundlePrefab(bundle: AssetManager.Bundle,path:string,cb?: (err:Error | null, asset?: Prefab)=>void) {
bundle.load(path,Prefab,cb);
}
public static inst3d(asset: Prefab, root:Node | undefined = undefined, pos:Vec3 = Vec3.ZERO) : Node {
try {
if (CF.isNull(asset)) {
return null;
}
const instObj = instantiate(asset);
if (root) {
instObj.setParent(root);
} else {
director.getScene().addChild(instObj);
}
instObj.setWorldPosition(pos);
instObj.setScale(Vec3.ONE);
return instObj;
} catch (error) {
console.error('实例模型异常对象:',asset);
console.error('实例模型异常:',error);
}
return null;
}
调用示例
Res.instBundlePrefab3d(Game.Instance._bundle_reslib,Game.Instance._objects_pool_node,new Vec3(p.x, p.y, p.z),resid,(err,asset)=>{
if(asset){
// 实现你的业务逻辑
}
});
其中 Game.Instance._objects_pool_node 为 Game文件中定义的全局变量 _objects_pool_node:Node | null | undefined; // 对象池节点 作为对象池
在Game文件初始化的时候执行
this._objects_pool_node = find('Main/objects_pool'); // 获取对象池节点对象
this._objects_pool_node.addComponent(ExitPointerLock);// 绑定支持锁定退出逻辑