Beginner
Beginner

Reputation: 67

action does not wait till function call ends

I have 2 actions that i put in a sequence. In the first action I am calling a method to calculate the new waiting time for the next action. The next action is just a wait for this duration, but the second action always executes straight away, so the time must be 0. I debugged it and in the method spawnFlowers i get the time returned as 3.5 seconds.

these are my 2 actions

let spawnFlowerAction = SKAction.run {
            self.WaitTime = self.calculateWaitingTime()
        }
let waitForNewFlower = SKAction.wait(forDuration: self.WaitTime)

I execute it this way:

        let spawnSeq = SKAction.sequence([spawnFlowerAction, waitForNewFlower])
        let spawnRepeat = SKAction.repeat(spawnSeq, count: 4)
        self.run(spawnRepeat)

Result: 4 times spawned without waiting, printing 4 different calculated times in the console from the calculateWaitingTime function (in which the spawning happens)

What is a good way to fix this?

Upvotes: 2

Views: 57

Answers (1)

KissTheCoder
KissTheCoder

Reputation: 679

The problem is trying to dynamically change the values used within SKActions after the action has been created. For example when your WaitTime variable changes while running the spawnFlowerAction, the waitForNewFlower Action's wait time won't change dynamically because it doesn't reference WaitTime. Instead its wait value is whatever your variable WaitTime was when you declared let waitForNewFlower = SKAction.wait(forDuration: self.WaitTime) (Which I'm guessing was initially 0). Same concept goes with your other two spawn actions.

I usually use the dispatch Queue for things like these, but to use SKActions here's a function. Just call it once and input the number of times you want it to repeat.

func spawnRepeat(count: Int) {

    //Put whatever code to spawn flower here
    print("SPAWN FLOWER")

    if count > 1 {
        //Recalculate WaitTime
        WaitTime = calculateWaitingTime()
        let waitAction = SKAction.wait(forDuration: WaitTime)
        run(waitAction, completion: { self.spawnRepeat(count: count - 1) })
    }
}

Upvotes: 1

Related Questions