Search code examples
iosswiftswift3sprite-kit

How do you make Swift wait for SKAction to be executed?


I have the following Swift code, however, when I run it in Xcode Simulator, it skips straight to "I don't believe we have met before". How do I make Swift wait for "Welcome" to be executed first?

import SpriteKit
import GameplayKit

class GameScene: SKScene {

override func didMove(to view: SKView) {

    // Get label node from scene and store it for use later

    let animateList = SKAction.sequence([SKAction.fadeIn(withDuration: 1.0), SKAction.wait(forDuration: 2.0), SKAction.fadeOut(withDuration: 1.0)])

    let startScreen = SKLabelNode(fontNamed: "Helvetica Neue UltraLight")
    startScreen.text = "Welcome"
    startScreen.fontSize = 100.0
    startScreen.fontColor = SKColor.white
    startScreen.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
    self.addChild(startScreen)
    startScreen.alpha = 0.0

    startScreen.run(animateList)

    startScreen.text = "I don't belive we have met before"

    startScreen.run(animateList)



    }


}

Solution

  • Instead of calling startScreen.run(), call startScreen.run(_:completion) and do the things you want to do after the SKActions have run inside the completion handler. See the documentation.

    startScreen.run(animateList, completion: {
        self.startScreen.text = "I don't belive we have met before"
        self.startScreen.run(animateList)
    })