Attempted to add a SKNode which already has a parent

Viewed 35

Please help. I'm doing a game with Swift 4. I want to make a loop that creates random grounds(and coins together) at different heights as a player comes down. But I got the error message.

Thread 1: "Attemped to add a SKNode which already has a parent: name:'(null)' texture:[ 'coin1' (359 x 357)] position:{865, 2030} scale:{1.00, 1.00} size:{100, 100} anchor:{0.5, 0.5} rotation:0.00"

class GameScene: SKScene...{ let platform = SKSpriteNode(imageNamed: "ground") let coin = SKSpriteNode(imageNamed: "coin1") let coin2 = SKSpriteNode(imageNamed: "coin2")

enum bitmasks: UInt32 {
    case player = 0b1
    case platform = 0b10
    case coin


override func didMove(to view: SKView) { ... makePlatform() }

func makePlatform() { let platform = SKSpriteNode(imageNamed: "ground") platform.position = CGPoint(x: GKRandomDistribution(lowestValue: 0, highestValue: 800).nextInt(), y: GKRandomDistribution(lowestValue: 1200, highestValue: 1225).nextInt() - Int(player.position.y - 1000))

coin.position = CGPoint(x: platform.position.x + 80, y: platform.position.y + 80) coin.zPosition = 6 coin.setScale(1)

addChild(coin)
addChild(platform) }

func didBegin(_ contact: SKPhysicsContact) {
if contactA.categoryBitMask == bitmasks.platform.rawValue && contactB.categoryBitMask == bitmasks.cameraLine.rawValue {
        contactA.node?.removeFromParent()
        makePlatform()}
1 Answers

Where are you creating coin? Can you show your code for where coin is created?

This problem often occurs when the programmer accidentally keeps trying to add the same sprite by having a loop that updates its position and add it via addChild, rather than creating a new sprite in each loop.

Does this solve your problem? :

https://stackoverflow.com/a/28407033/1430420

Related