一、 問題背景
有時(shí)候拇颅,當(dāng)我們場景上掛載的資源過多時(shí)奏司,我們使用cc.director.loadScene切換場景時(shí)會等一段時(shí)間才會切換過去,這對游戲的體驗(yàn)是相當(dāng)不好的樟插。所以我們可以使用cc.director.preloadScene來進(jìn)行預(yù)加載韵洋,如:https://space.bilibili.com/351545447
cc.director.preloadScene("sceneName", function () {
cc.director.loadScene("sceneName");
});
同時(shí)搭載一個(gè)加載進(jìn)度條來實(shí)現(xiàn)顯示加載進(jìn)度,優(yōu)化游戲體驗(yàn):
二黄锤、 如何獲取加載時(shí)的進(jìn)度搪缨?
- Cocos Creator 2.0版本之前
在Cocos creator 2.0版本之前,我們可以使用下面這樣的方法:
cc.loader.onProgress = function (completedCount, totalCount, item){
//先開監(jiān)聽
this.loading.progress = completedCount/totalCount;
this.loadLabel.string = Math.floor(completedCount/totalCount * 100) + "%";
}.bind(this);
cc.director.preloadScene("sceneName", function () {
cc.log("加載成功");
});
備注:loading就是你在腳本中綁定的進(jìn)度條組件鸵熟。
- Cocos Creator 2.0版本之后
Cocos creator升級到2.0版本后副编,onProgress貌似就無法使用了,所以上述那個(gè)方法無法獲取到加載進(jìn)度流强,但是在cc.director.preloadScene這個(gè)函數(shù)中新增了一個(gè)參數(shù):
所以我們可以通過這個(gè)參數(shù)來獲取加載的進(jìn)度:
cc.director.preloadScene("sceneName", this.onProgress.bind(this), function(){
cc.log("加載成功")痹届;
})
**onProgress** :function(completedCount, totalCount, item){
this.loading.progress = completedCount/totalCount;
this.loadLabel.string = Math.floor(completedCount/totalCount * 100) + "%";
}
三、 源碼角度分析本質(zhì)
其實(shí)無論是預(yù)加載場景還是加載資源煮盼,本質(zhì)調(diào)用的還是cc.loader.load這個(gè)api短纵,看底層代碼可以知道带污,源碼部分截圖如下:
- 預(yù)加載場景
- 加載資源
而cc.loader.load的內(nèi)部實(shí)現(xiàn)的參數(shù)中就是帶有這個(gè)回調(diào)函數(shù)的僵控,如下圖:
四、 結(jié)論
所以我們還可以這樣寫來獲取加載場景的進(jìn)度:
var info = cc.director._getSceneUuid(this.sceneName);
var self = this;
if (info) {
cc.loader.load({ uuid: info.uuid, type: 'uuid' }, function(completedCount, totalCount, item){
cc.log("已完成Items:" + completedCount);
cc.log("全部Items:" + totalCount);
cc.log("當(dāng)前Item:" + item.url);
self._loadingNextStep = parseInt(completedCount / totalCount * 100);
cc.log("加載進(jìn)度:" + self._loadingNextStep);
}, function(error, asset){
if (error) {
cc.errorID(1210, this.sceneName, error.message);
} else {
cc.log("加載完成");
}
}
});
}