resCount resTotal為文件統(tǒng)計(jì)申钩,resTotal需在init中賦值次绘,賦值大小必須與pathList文件夾下文件總和相等,否則會(huì)加載不全典蜕。
pathList中的路徑為相對(duì)Resources文件夾下的路徑断盛,所以為了方便起見(jiàn),不建議在Resources下直接存放資源文件
頭文件
#ifndef LoadingScene_hpp
#define LoadingScene_hpp
#include <stdio.h>
#include "cocos2d.h"
class LoadingScene : public cocos2d::Layer
{
private:
unsigned int resCount;
unsigned int resTotal;
std::list<std::string> pathList;
public:
static cocos2d::Scene* createScene();
virtual bool init();
std::list<std::string> getFilesFromPath(std::string path);
void loadResources();
void loadCallback(cocos2d::Ref* pSender);
CREATE_FUNC(LoadingScene);
};
#endif /* LoadingScene_hpp */
源文件
#include "LoadingScene.hpp"
//以下是遍歷文件所需頭文件
#include <sys/stat.h>
#include "dirent.h"
#include "unistd.h"
USING_NS_CC;
Scene* LoadingScene::createScene()
{
auto scene = Scene::create();
auto layer = LoadingScene::create();
scene->addChild(layer);
return scene;
}
bool LoadingScene::init()
{
resCount = 0;
resTotal = 100;
pathList.clear();
pathList.push_back("images");
pathList.push_back("images/images2");
this->loadResources();
return true;
}
std::list<std::string> LoadingScene::getFilesFromPath(std::string path)
{
std::list<std::string> files;
std::string filePath = FileUtils::getInstance()->fullPathForFilename(path);
DIR *dp;
struct dirent *entry;
struct stat statbuf;
dp=opendir(filePath.c_str());
chdir(filePath.c_str());
while((entry=readdir(dp))!=NULL)
{
stat(entry->d_name,&statbuf);
if(!S_ISREG(statbuf.st_mode))
continue;
files.push_back(path+"/"+entry->d_name);
}
return files;
}
void LoadingScene::loadResources()
{
CCLOG("start loading");
while(pathList.size()>0)
{
std::list<std::string> files=getFilesFromPath(pathList.back());
while(files.size()>0)
{
Director::getInstance()->getTextureCache()->addImageAsync(files.back(), CC_CALLBACK_1(LoadingScene::loadCallback, this));
CCLOG("loading %s",files.back().c_str());
files.pop_back();
}
pathList.pop_back();
}
}
void LoadingScene::loadCallback(cocos2d::Ref *pSender)
{
resCount++;
if (resCount == resTotal)
{
//加載完成就切換場(chǎng)景
}
}