Switching sprites with setSpriteFrame/getSpriteFrameByName

Hi all
I’m trying to change a sprite image. I’ve done this before in my game and it works fine with the following method:

Now I’m trying the following code at another location but for some reason SpriteFrameCache::getInstance()->getSpriteFrameByName("SpriteFrameName") returns nullptr, meaning it couldn’t find the SpriteFrameName. On debug mode however I did manage to find the SpriteFrameName as part of SpriteFrameCache.
Furthermore I was passing SpriteFrameCache::getInstance() from my main game class to a custom object, even though SpriteFrameCache is a singleton class so it should exist and be accessible anyway.

What am I missing here, how come I receive nullptr? Any advice would be more than welcome!

It would be quicker for you to find out why by stepping through your code in a debugger to the point where it returns the nullptr, that way there will be no guessing as to what may be the issue.

1 Like

@R101 I did… it (CCMAP) fails to find the frame texture name and therefore returns nullptr.

Post more code, formatted in an easy to read manner

That is not possible. If, as you stated, it exists in the map, then there is no way it won’t return the value, unless the value associated with the key is a nullptr. Have you checked to ensure that isn’t the case?

You mentioned a custom object that you’re passing the instance pointer of SpriteFrameCache to; is that by any chance running in a separate thread?

Other than that, have you checked the string to ensure it is in fact the exact same as the key entry in the map (character case/missing characters etc)? I realise this is stating the obvious, but just in case.

Also, as @slackmoehrle remarked, posting the relevant code would go a long way to helping you diagnose the source of this issue.

Hey @R101, @slackmoehrle thanks for your suggestions.
The issue was on my side - as I mentioned I have a custom object (inherits from Node). I moved some code around and I was adding children to the object before setting its content size. this caused the children to appear but off-screen. You could easily think they are not there.
What threw me off is the fact that SpriteFrameCache doesn’t store the texture name - it got me thinking that might be the issue here.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.