效果![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/202c6c9ee02fca506a47db1104665dcc.gif#pic_center)
loadingFrame.js
cc.Class({
extends: cc.Component,
properties: {
hello: cc.Prefab,
content: cc.Node,
mask: cc.Node,
// animation: cc.Animation,
},
onLoad() {
this.mask.active = false;
// this.animation.node.active = false;
},
click() {
// for (let index = 0; index < 500; index++) {
// let temp = cc.instantiate(this.hello);
// temp.parent = this.content;
// temp.getComponent(cc.Label).string = index + 1;
// }
// 分帧加载
let cb = (i) => {
let temp = cc.instantiate(this.hello);
temp.parent = this.content;
temp.getComponent(cc.Label).string = i;
};
this.mask.active = true;
// this.animation.node.active = true;
// this.animation.play();
this._loadPrefabFrame('test', 2, 500, cb);
},
/**
*
* @param {string} name 给计时器分配一个name
* @param {number} limit 每帧至少加载几个prefab
* @param {number} max 最大加载的prefab数量
* @param {function} cb 加载代码
*/
_loadPrefabFrame(name, limit, max, cb) {
let count = 0;
this[name] = () => {
if (count < max) {
for (let i = 0; i < limit; i++) {
count++;
cb && cb(count);
//关闭动画
if (count === max - 1) {
this.mask.active = false;
// this.animation.stop();
// this.animation.node.active = false;
}
}
}
};
this.schedule(this[name], 1 / 60, (max - 1) / limit, 0);
},
});
使用
总结问题
Cocos Creator 采用 Java Script/Type Script语言开发,本质上就是JS。而JS是单线程的,如果使用不当,在同一帧加载或者销毁太多的资源,极有可能导致界面卡顿。
解决方法
将在一帧内要处理的资源,手动分为多次加载每一帧加载处理部分资源,这样我们就可以有计划的处理这些资源,也不会造成卡顿。本质上就是牺牲时间,换流畅。同时,我们也需要注意牺牲的时间要是太长,同样会造成用户不爽,因此我们要把握住这个度。