Check for Sprite Parent

In my game, on certain action iam removing Sprites from scene

sampleSprite->removeFromParent();

but sprites are still present in the vector

std::vector<Sprite*> spriteContainer;

When i do check for parent of each sprites from vector in loop as i do need to check according to gameplay
//gameloop
spriteContainer.at(loopCount)->getParent();

Game is crashing when it tries to access those sprites which are earlier removed,
I know i have to delete those sprites from vector which iam doing later, but in gameloop call to those sprite comes before its deleted. And it crashes

So, how can in check whether sprite have parent or not
Or more like whether sprite is added to scene or not …
Help Needed.

removeFromParent() reduces reference count of the Sprite so it’s getting cleaned from memory. That’s why accessing it later crashes the game. If you want to still hold them easiest way is to use Vector instead of vector (it’s a std::vector clone with adding reference count when object is added to the Vector).

2 Likes

Thanks for advice, now i have used cocos Vector as you suggested first … still crashed.
Then i also tried to retain() that sprite and release() manually … still not positive.
i’am really stuck here … like no hope found :joy::joy:

Split the code:

auto item = spriteContainer.at(loopCount);
first check if item is nullptr or not.
then try calling getParent()

I can see three reasons why it crashes:

  1. loopCount is out of bounds
  2. spriteContainer.at(loopCount) is nullptr
  3. item doesn’t have a parent, so the getParent() gives nullptr
1 Like

Yes , the third reason is absolutely correct …
The Child has been removed from parent that is why crash occurring
But i did check whether sprite->getParent() returns nullptr but that’s the time when it’s getting crashed
cause child ( Sprite ) doesn’t have any parent …
But i did resolved this issue by setting tag to each sprite whenever i removing it and further checked in loop for
sprite->getTag() != myTag
And finally it did worked … Thanks for pointing out that issue.

Glad it helped, cheers.