I want to access a sprite in a scene, but I cannot get the running scene from outside the scene class.

The scene is created using:

Scene* MyScene::createScene() {
    auto scene = Scene::create();
    auto layer = MyScene::create();
    return scene;

bool MyScene::init() {
    this->addChild(sprite,100, 1234);

But if I then access the running scene from outside the class, it has no children.

//should be the MyScene instance with sprite children, but has no children.

I also tried giving the scene layer a tagname, but with the same result.

//returns NULL because getRunningScene has no children.

The only way I can access the scene is making a static reference in my AppDelegate, but this doesn't seem a proper way. How can I get the current scene correctly from outside the class?

  • \$\begingroup\$ I think this question is duplicate of this one. \$\endgroup\$
    – Emadpres
    May 24 '15 at 5:19

Your layer is a child of scene.

Try a Director::getInstance()->getRunningScene()->getChildrenCount() and you will find only 1 child: layer

You will have to search the children of layer to find the one you need :)

I would use:

auto scene = Scene::create();
auto layer = HelloWorld::create();
scene->addChild(layer,0,999); // add layer as a child to scene

In the init():

this->addChild(yourNode,100,TAGNAME); //this points to layer!

To find yourNode with tag

auto scene = cocos2d::Director::getInstance()->getRunningScene();
auto layer = scene->getChildByTag( 999 );
auto node = layer->getChildByTag( TAGNAME );

I think this will answer your question.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.