0
votes

Can you tell me why this code doesn't work? Isn't it possible to run an Action in a SKAction.runBlock()-function?

let testaction = SKAction.repeatActionForever(SKAction.runBlock({self.myFunction()}))
runAction(testaction)

Here is my testaction:

func myFunction() {
    runAction(SKAction.runBlock({
      let i = 0
      print(i)
    }))
}

I need this for a game. I want to distinguish some cases in myFunction to run different Actions in different cases. What have i done wrong?

Edit: When i change myFunction() to this, i get printed the 1 forever, but not the 0 from the inside runBlock.

func myFunction() {
    let j = 1
    print(j)
    runAction(SKAction.runBlock({
      let i = 0
      print(i)
    }))
}
1
What exactly happens if you try it?J Fabian Meier
Nothing. No output and no error, just running forever.SwiftProgger
Calling runAction doesn't cause an action to run, it just queues an action to be run the next time the scene's animation loop is processed. I'm guessing that since you're constantly adding actions to that queue (without even any delay), that animation loop never gets processed. If you don't repeat that forever, but instead run X times, you'll see a bunch of 1s followed by a bunch of 0s.Ben Kane
You are basically in a very quickly executing infinite loop queueing those actions. Are you sure this is what you need to do? Are you sure you don't need to do something more like run an action once every second and repeat forever?Ben Kane
@SwiftProgger From the docs : "The action to be repeated must have a non-instantaneous duration." Checkout my answer here : stackoverflow.com/a/30732945/3402095 ... When runBlock is executed an action take place instantaneously. So, you are not using repeatActionForever as it meant to be used.Whirlwind

1 Answers

0
votes

Like people above have said you just need to add a slight delay to it and it should work

  let testaction1 = SKAction.runBlock(self.myFunction)
  let testaction2 = SKAction.waitForDuration(0.1)
  let sequence = SKAction.repeatActionForever(SKAction.sequence([testaction1, testaction2]))

  runAction(sequence)