diff --git a/cocos/2d/CCRenderTexture.h b/cocos/2d/CCRenderTexture.h index f6a83c0ef2..345eba3c4e 100644 --- a/cocos/2d/CCRenderTexture.h +++ b/cocos/2d/CCRenderTexture.h @@ -107,6 +107,9 @@ public: /** saves the texture into a file. The format could be JPG or PNG. The file will be saved in the Documents folder. Returns true if the operation is successful. + Notes: since v3.x, saveToFile will generate a custum command, which will be called in the following render->render(). + So if this function is called in a event handler, the actual save file will be called in the next frame. If we switch to a different scene, the game will crash. + To solve this, add Director::getInstance()->getRenderer()->render(); after this function. */ bool saveToFile(const std::string& filename, Image::Format format, bool isRGBA = true, std::function callback = nullptr); diff --git a/tests/cpp-tests/Classes/RenderTextureTest/RenderTextureTest.cpp b/tests/cpp-tests/Classes/RenderTextureTest/RenderTextureTest.cpp index 8389cffb8e..4f3b51154c 100644 --- a/tests/cpp-tests/Classes/RenderTextureTest/RenderTextureTest.cpp +++ b/tests/cpp-tests/Classes/RenderTextureTest/RenderTextureTest.cpp @@ -146,7 +146,8 @@ void RenderTextureSave::saveImage(cocos2d::Ref *sender) }; _target->saveToFile(png, Image::Format::PNG, true, callback); - + //Add this function to avoid crash if we switch to a new scene. + Director::getInstance()->getRenderer()->render(); CCLOG("Image saved %s", png); counter++;