5

I'm trying to addChild after 2 seconds the user touched the screen (it is inside touchesBegan), but it doesn't work. Am I doing anything wrong?

//show myLabel after 2 seconds
self.myLabel.position = CGPoint(x: self.frame.width / 1.1, y: self.frame.height / 2)
self.myLabel.text = "0"
self.myLabel.zPosition = 4

self.myLabel.runAction(SKAction.sequence([SKAction.waitForDuration(2.0), SKAction.runBlock({
    self.addChild(self.myLabel)
)]))
Luiz
  • 1,275
  • 4
  • 19
  • 35

2 Answers2

8

The problem is that the actions won't run on myLabel unless it is in the scene, so change the last part into :

self.runAction(SKAction.sequence([SKAction.waitForDuration(2.0), SKAction.runBlock({
    self.addChild(self.myLabel)
})]))

Or better:

self.runAction(SKAction.waitForDuration(2)) {
    self.addChild(self.myLabel)
}

Note: I assume here that self is a scene or some other node that is already added to the scene.

smallfinity
  • 141
  • 5
  • The second one worked, but i had to change some things (instructed by xcode). It ended up being: `self.runAction(SKAction.waitForDuration (2.0), completion: { self.addChild(self.myLabel) })` – Luiz Apr 03 '16 at 00:47
  • You are welcome! I've edited my answer after testing it in Xcode. If the answer helps you, please consider voting and/or accepting it :) – smallfinity Apr 03 '16 at 00:50
  • 1
    make sure to do `{[unowned self] in self.addChild(self.myLabel)}` The closure is going to hold onto self, so it won't dealloc. This is called a retain cycle, you can search for more info on the matter. – Knight0fDragon Apr 04 '16 at 16:01
-1

You can declare this function, where you want

public func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
           DISPATCH_TIME_NOW,
           Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
 }

and using as:

   delay(2.0) {
      self.addChild(self.myLabel)
   }