How to disable auto disposing Sprites?

I have a sprite in main menu of my game. When the game starts, I add this sprite to the scene. And when the player taps on “Play” button, I start the game and remove this sprite. Because it was meant to stay in just main menu, not game.

Anyway, what if I return back to the main menu? I try adding this sprite again, to the scene but… It gives me nullptr error because it seems like it’s auto disposed from the memory. I can’t use it again!

I tried using retain() after removing the sprite. But it doesn retain, it doesnt work. My sprite keeps getting auto released from memory.

Is there any other way to disable auto disposal of my sprite? Like…

sprMenuLogo->setAutoRelease(false);

or…

sprMenuLogo->retainForever();

Please help. Thanks.

show more code, please.

Here is the code that calls when the player clicks on Play button:

void HelloWorld::startGame() {

    auto callbackMenuRemoved = CallFunc::create([&]() {

        this->removeChild(sprBottomContainer);
        sprBottomContainer->retain();
    });

    auto easeMove2 = EaseBackIn::create(MoveBy::create(0.5f, Vec2(0.f, -sprBottomContainer->getContentSize().height)));
    auto seq = Sequence::create(easeMove2, callbackMenuRemoved, NULL);
    
    sprBottomContainer->runAction(seq);
}

And here’s the code that calls when user returns to the menu:

void HelloWorld::returnToMenu() {

	sprBottomContainer->setPosition(origin.x + (visibleSize.width*0.5f), origin.y + 5.f);

	this->addChild(sprBottomContainer);
}

And here is the error

errordamn

You are removing it. Once removed, the retain() will crash as it is gone.

1 Like

How about use sprite->setVisible(false) instead of removeChild(sprite) each time?

1 Like

Use this:

sprBottomContainer->retain();
sprBottomContainer->removeFromParentAndCleanup(false);

Also, don’t forget to release it, when leaving a scene:

sprBottomContainer->release();
2 Likes

Thanks all for replies. I used sprite->setVisible(false) instead and solved the problem.