Cocos Creator 准确获取场景加载进度

目前Cocos Creator切换场景推荐使用

cc.director.loadScene(sceneName);

预加载:

cc.director.preloadScene(sceneName,completeCallback);

如果是本地资源,这两个方法也够用了。最近搞微信小游戏,远程资源加载没有进度控制,就显得很无力。
cc.loader.load方法是可以获取加载进度,cc.director.preloadScene也是调用的相同的方法,但是并没有把progressCallback暴露出来,o(╥﹏╥)o自己动手丰衣足食吧。

upload successful

照着preloadScene方法画个瓢

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
cc.Class({
extends: cc.Component,
properties: {
label: {
default: null,
type: cc.Label
},
text: 'Loading',
sceneName: "menuScene",
_loadingPercent: 0,
_loadingNextStep: 0
},

// use this for initialization
onLoad: function () {
this.label.string = this.text;

var info = cc.director._getSceneUuid(this.sceneName);
var self = this;
if (info) {
cc.loader.load({ uuid: info.uuid, type: 'uuid' }, (completedCount, totalCount, item) => {
cc.log("已完成Items:" + completedCount);
cc.log("全部Items:" + totalCount);
cc.log("当前Item:" + item.url);
self._loadingNextStep = parseInt(completedCount / totalCount * 100);
cc.log("加载进度:" + self._loadingNextStep);
}, (error, asset) => {
if (error) {
cc.errorID(1210, this.sceneName, error.message);
} else {
cc.log("加载完成");
}
});
}
},

// called every frame
update: function (dt) {
this._loadingPercent++;
this._loadingPercent > this._loadingNextStep ? this._loadingNextStep : this._loadingPercent;
this.label.string = this.text + this._loadingPercent + "%";
if (this._loadingPercent >= 100) {
this.label.string = this.text + "100%";
this.node.runAction(cc.sequence(
cc.fadeOut(0.5),
cc.delayTime(0.5),
cc.callFunc(() => {
cc.director.loadScene(this.sceneName);
}, this)
));
}
},
});

实测,这个可以准确获取场景加载的进度。
继续干活了

补充:

this.emit(cc.Director.EVENT_BEFORE_SCENE_LOADING, sceneName);

这行代码也得加上,少了这个事件,会报错。

upload successful