Say I have a button which is displaying “1.png”.
I now change “1.png” using FileUtils::getInstance()->writeStringToFile() and want the button’s image to change to the new “1.png”. I’ve tried using btn->loadTextureNormal(“1.png”) but it doesn’t work for me.
Is there a proper way to do this? Or do I have to delete the old button and create a new one?
In cocos2d-x, files with the same path are cached,
Even if you change the contents of the file, the display does not change as it is.
You need to clear the cache.
From my understanding, the test is using btn->loadTextureNormal() which is what I have tried. However, it only sometimes works. I have tried clearing the cache like @bluewind00 has suggested but it still only sometimes works. Also, the filename is the same name, before and after.
Button *btn = Button::create();
btn->loadTextureNormal(imagePath);
btn->setPosition(position);
btn->addTouchEventListener([=](Ref* sender, Widget::TouchEventType type) {
.
//if you want to change the button image when you touch the button, is better to make a separate method instead of this one, and use loadTextureNormal, changing this property in the already added button
.
});
this->addChild(btn);
If you want to change the button’s image, you should have 2 different images/filenames (the original, and the new one)
I just tried it again and it now works. It seems that I had something elsewhere that was preventing the images from updating properly.
Note:
I don’t need to clear the cache.
The filename can be the same before and after.
I used btn->loadTextureNormal("filename") where btn is a ui::Button.