Component children look up

Hi, I’ve attached a component I created to some nodes in a scene like this

class SomeComponent : public cocos2d::Component {
  SomeComponent() {
    setName(__func__); // sets name to SomeComponent 
    setOwner(node);
    setEnabled(true);
  }
}

auto component = new SomeComponent();
node->addComponent(component);

the problem here is how do i search and get pointers to those nodes that have that component in a scene?

I do not care about performance as this search can happen rarely

I can ask engineering to have a look. What version of cocos2d-x are you using?

i use cocos2dx v4.0

Iterate through all the children of the scene, using Node::getComponent(const std::string& name) to try to get.

Yeah that’s what I was thinking about, but there is another problem which is how to look for nodes that are inside nodes that are inside nodes and so on… something like a file search

I found a way on how to do it after a lot of thinking, which is

// WARNING: Returns nullptr if nothing is found, please check if return pointer is nullptr to avoid problems
// the 'list' argument should be left nullptr, it's only used for the recursive search
inline std::vector<Node*>* findComponentsByName(Node* parent, std::string name, bool containParents = true, std::vector<Node*>* list = nullptr)
        {
            std::vector<Node*>* nodes = list == nullptr ? new std::vector<Node*>() : list;

            if (parent->getChildrenCount() == 0)
                return nullptr;

            bool hasFoundSomething = false;

            for (auto i : parent->getChildren())
            {
                if (i->getChildrenCount() > 0 && containParents)
                {
                    if (i->getComponent(name) != nullptr)
                    {
                        nodes->push_back(i->getComponent(name)->getOwner());
                        hasFoundSomething = true;
                    }
                }
                else if (i->getChildrenCount() == 0 && !containParents)
                {
                    if (i->getComponent(name) != nullptr)
                    {
                        nodes->push_back(i->getComponent(name)->getOwner());
                        hasFoundSomething = true;
                    }
                }

                if (i->getChildrenCount() > 0)
                    findComponentsByName(i, name, containParents, nodes);
            }

            if (list == nullptr)
            {
                if (hasFoundSomething)
                    return nodes;
            }

            return nullptr;
        }

It’s kinda bad and unoptimized but it does the job for me! Thanks for the help <3

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.