Need help making images unload

Hello - I have some code here that when an image (which is my button) is clicked, a new image randomly appears. This is due to a table I created with some images inside.

local animalPic local button = display.newImageRect ("images/animalBtn.jpg", 200, 200) button.x = 250 button.y = 50 local myPics = {"images/animal1.png", "images/animal2.png"} function button:tap (event) local idx = math.random(#myPics) local img = myPics[idx] local animalPic = display.newImage(img) animalPic.x = contentCenterX animalPic.y = contentCenterY end button:addEventListener ("tap", button)

The problem with it is the graphics just keep piling up when I click the button. The correct behavior should be -

Button is clicked and an image is shown while removing the previous image. How do I incorporate this behavior? I already tried the removeSelf command and it doesnt work…Any help appreciated.

You need to remove the first one before you recreate it… something like:

    if animalPic and animalPic.removeSelf then            animalPic:removeSelf()            animalPic = nil     end    animalPic = display.newImage(img)

You already have it forward declared at the top, so you’re good there, just drop the local.

Thank you Mr. Rob Miracle. I appreciate your insight. The example you provided works well. I see from your example that the problem that I was having with the “removeSelf” command was that I was not encapsulating it inside an IF statement. I was actually putting it inside my function that I was using when the button is clicked - like this

function button:tap (event) animalPic:removeSelf() animalPic = nil local idx = math.random(#myPics) local img = myPics[idx] animalPic = display.newImageRect (img, 265, 115) animalPic.x = 240 animalPic.y = 135 end

Anyhow, Thanks again! :smiley:

You need to remove the first one before you recreate it… something like:

    if animalPic and animalPic.removeSelf then            animalPic:removeSelf()            animalPic = nil     end    animalPic = display.newImage(img)

You already have it forward declared at the top, so you’re good there, just drop the local.

Thank you Mr. Rob Miracle. I appreciate your insight. The example you provided works well. I see from your example that the problem that I was having with the “removeSelf” command was that I was not encapsulating it inside an IF statement. I was actually putting it inside my function that I was using when the button is clicked - like this

function button:tap (event) animalPic:removeSelf() animalPic = nil local idx = math.random(#myPics) local img = myPics[idx] animalPic = display.newImageRect (img, 265, 115) animalPic.x = 240 animalPic.y = 135 end

Anyhow, Thanks again! :smiley: