用cocos 生成的Login工程,加了个loadingbar,但是在监听事件添加后,单击login按钮,中断,提示BAR为null,求大神解答。
代码如下
helloworld.cpp的
请把代码粘贴在这里
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
auto rootNode = CSLoader::createNode("MainScene.csb");
addChild(rootNode);
Button* login = dynamic_cast (seekNodeByName(rootNode, std::string("Button_1_2_6_10")));
LoadingBar* Bar = (LoadingBar*)seekNodeByName(rootNode, std::string("Bar"));
Bar->setPosition(Vec2(390, 390));
Bar->setPercent(Bar->getPercent() + 80);
login->setPosition(Vec2(200, 200));
login->addTouchEventListener(CC_CALLBACK_2(HelloWorld::onClicks, this));
logout = (Button*)seekNodeByName(rootNode, std::string("Button_1_0_4_8_12"));
logout->setPosition(Vec2(400, 400));
logout->setTag(10);
return true;
}
Node * HelloWorld::seekNodeByName(Node * root, std::string & name)
{
if (!root)
return nullptr;
if (root->getName() == name)
return root;
const auto& arrayNode = root->getChildren();
for (auto& child : arrayNode)
{
Node* pNode = dynamic_cast(child);
if (pNode)
{
Node* res = seekNodeByName(pNode, name);
if (res)
return res;
}
}
return nullptr;
}
void HelloWorld::onClicks(Ref * sender, cocos2d::ui::Widget::TouchEventType type)
{ switch (type) {
case Widget::TouchEventType::BEGAN:
break;
case Widget::TouchEventType::ENDED:
//Button* logout = (Button*)logout->getChildByTag(12);
if (logout->isVisible()) {
logout->setVisible(false);
}
else {
logout->setVisible(true);
}
Bar->setPercent(Bar->getPercent() - 10);
break;
}
}
```
helloworld.h的
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
Node * HelloWorld::seekNodeByName(Node * root, std::string & name);
cocos2d::ui::Button* login;
cocos2d::ui::Button* logout;
cocos2d::ui::LoadingBar* Bar;
void HelloWorld::onClicks(Ref* sender,cocos2d::ui::Widget::TouchEventType type);
```