cocos2dx 如何获得节点的类型

时间:2023-03-10 06:43:57
cocos2dx 如何获得节点的类型

1. 需求:在所有子节点中得到是ui::Text类型的节点,并对其进行操作。

2. 解决方案:在根节点Node中有一个如下的函数:

    /**
* Gets the description string. It makes debugging easier.
* @return A string
* @js NA
* @lua NA
*/
virtual std::string getDescription() const;

Node中默认的实现:

std::string Node::getDescription() const
{
return StringUtils::format("<Node | Tag = %d", _tag);
}

我们在ui::Text中找到该函数的实现如下:

std::string Text::getDescription() const
{
return "Label";
}

修改为:

std::string Text::getDescription() const
{
return "cocos2d::ui::Text";
}

3.我们在遍历子节点时就可以知道节点的类型是不是cocos2d::ui::Text了

        for (Vector<Node*>::iterator it = all_children.begin(); it != all_children.end(); ++it){
Node* child = *it;
std::string type_name = child->getDescription();
if (type_name == "cocos2d::ui::Text"){
//DO SOMETHING
}
}

以上,完。