[SOLVED] Call method of running scene when AppDelegate::applicationDidEnterBackground()

Hi, I wan to hide some sprites when the user reopens the game after he pressed the home button. What is the best solution? Thanks :slight_smile:

There is a function in CCDirector, GetRunningScene.

If your scene class has a function where you hide your sprites then you should be able to call that function from the AppDelegate class.

Do you have any code ? Say that my scene has a function called hideSprites();

CCDirector::sharedDirector()->getRunningScene()->hideSprites(); // Doesn’t seem to work

Thank you

Cast pointer returned by getRunningScene() to proper type with dynamic_cast first. Similar topic: http://www.cocos2d-x.org/boards/6/topics/10779

Thank you.

But I get exc_bad_access whenever that function tries to edit a variable of the running scene. What could be wrong.

// This function will be called when the app is inactive. When comes a phone call,it’s be invoked too
void AppDelegate::applicationDidEnterBackground()
{
LevelPlay* theScene = dynamic_cast < LevelPlay*>(cocos2d::CCDirector::sharedDirector()->getRunningScene()>getChildByTag);
theScene
>onSleep();
//
CCDirector::sharedDirector()->stopAnimation();
SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
SimpleAudioEngine::sharedEngine()->pauseAllEffects();
}

You should check for NULL after dynamic_cast because running scene might not be LevelPlay.

LevelPlay* theScene = dynamic_cast < LevelPlay*>(cocos2d::CCDirector::sharedDirector()->getRunningScene()->getChildByTag(1));
if (theScene != NULL)
{
     theScene->onSleep();
}

Also if you wrote it like that then I’m assuming LevelPlay is a CCLayer which you added to the scene with tag = 1 right?

Thank you. That was the problem… Now with the test theScene != NULL it doesn’t crash anymore but the sprites arent hidden.

Maybe I actually did not add a tag on the LevelPlay scene, how to do that?:

class LevelPlay : public cocos2d::CCLayer {
…

And what is the way to test also, if the returned pointer is actually of type LevelPlay in addition of the test if it is not NULL.

Thanks.

A dynamic cast will only return something if the type is correct, that is what the null check is for.

Dorin GRIGORE wrote:

Maybe I actually did not add a tag on the LevelPlay scene, how to do that?:

You can set a tag for this layer when you are adding it as a child of a scene. For example:

scene = CCScene::create();
MyLayer* mylayer= MyLayer::create();
scene->addChild(mylayer, 1, 12345); // 12345 is tag

Dorin GRIGORE wrote:

And what is the way to test also, if the returned pointer is actually of type LevelPlay in addition of the test if it is not NULL.

Your code actually is already doing it. dynamic_cast returns NULL if your object is not of the type you are trying to cast it to.

Thank you guys! Everything works great now! And very good to know about dynamic_cast and scene tag! :slight_smile: