Search code examples
iosswiftsprite-kitskspritenode

removeFromParent doesn't work with SKSpriteNode


I want to remove a sprite when I tap a button in my scene. The button is only enabled if the player collides with an item. This is the code for add and removes the sprite:

var imageShown = false
var imageForRiddle = SKSpriteNode()

func buttonAPressedForItem(item: WorldItem){
    if item.riddleImage != ""{
        imageForRiddle = SKSpriteNode(texture: SKTexture(imageNamed: item.riddleImage), color: .clear, size: CGSize(width: self.frame.size.width / 2, height: self.frame.size.height / 2))
        if !imageShown{
            imageForRiddle.position = player.position
            imageForRiddle.zPosition = 150
            self.addChild(imageForRiddle)
            imageShown = true
            print("Sprite added!")
        }
        else{
            imageForRiddle.removeFromParent()
            imageShown = false
            print("Sprite removed!")
        }
    }

The behaviour should be that if I touch the button, the image shows up. And if I touch the button again, the image dissapears. But the only thing happens is that the image shows up when I tap the button but never removed. When I click 3 times, I see the image 3 times. Both print statements are executed, so the imageForRiddle.removeFromParent is definitely called.

Does anyone know what is the problem here?


Solution

  • You created a new imageForRiddle on each tap with:

    imageForRiddle = SKSpriteNode(texture: SKTexture(imageNamed: item.riddleImage), color: .clear, size: CGSize(width: self.frame.size.width / 2, height: self.frame.size.height / 2))
    

    So, you are making a new image, then removing it (but, it was never added, so that is ignored).

    You need to use the property you made to store the image and make sure to make only one and remove and add the exact same object.

    Something like:

    var imageForRiddle: SKSpriteNode? = nil
    

    then,

    if imageForRiddle = nil {
        imageForRiddle = SKSpriteNode(texture: SKTexture(imageNamed: item.riddleImage), color: .clear, size: CGSize(width: self.frame.size.width / 2, height: self.frame.size.height / 2))      
    }
    

    and then unwrap imageForRiddle when you use it.