3
\$\begingroup\$

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(); scene->addChild(layer); 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.

Director::getInstance()->getRunningScene() //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.

scene->addChild(layer,100,TAGNAME); ... Director::getInstance()->getRunningScene()->getChildByTag(TAGNAME) //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?

\$\endgroup\$
1
  • \$\begingroup\$ I think this question is duplicate of this one. \$\endgroup\$ Commented May 24, 2015 at 5:19

1 Answer 1

2
\$\begingroup\$

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.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.