resCount resTotal为文件统计,resTotal需在init中赋值,赋值大小必须与pathList文件夹下文件总和相等,否则会加载不全。
pathList中的路径为相对Resources文件夹下的路径,所以为了方便起见,不建议在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)
{
//加载完成就切换场景
}
}
网友评论