Jonah Begood
Jonah Begood

Reputation: 317

SpriteKit SKAction.runBlock passing parameter issue

I'm experiencing some weird behavior using SKAction.runBlock. Basically I'm using the following syntax :

AnAction = SKAction.runBlock({ SomeFunction(SomeParameter) })

in a switch statement in which I have 100+ case

IDTargetSprite = FindTargetSprite()
TypeSprite = FindTypeSprite(IDTargetSprite)

switch TypeAction
{
...
case eTypeAction.DropBomb.rawValue:
    ActionBuilt = SKAction.runBlock({ DropBomb(IDTargetSprite) })

case eTypeAction.DropStar.rawValue:
    dParamsAction = LoadParamsAction()
    ActionBuilt = SKAction.runBlock({ DropStar(IDTargetSprite, dParamsAction) })
...
}

This code is included in a loop at the beginning of the program in which I go over an array of TypeAction

for TypeAction in tTypeAction
{
    // execute above code
}

then I execute the actions like this in another loop later :

switch TypeSprite
{
case eActionTarget.SpriteA.rawValue:
    SpriteA.runAction(ActionBuilt)

case eActionTarget.SpriteB.rawValue:
    SpriteB.runAction(ActionBuilt)
}

So far nothing unusual, except that it does not work and when I try to understand why I see that the parameter passed to the block is not good but in a very weird way : some times the parameter passed to the function in the block (IDTargetSprite or dParamsAction) does not have the right value inside the function called, it kept the value he just had in the previous iteration of the loop.

In these cases, if I look at the value of the parameter just before the runBlock lines, the value is right but when the action is executed the value found within the function called is not right anymore and equal to the value of the previous iteration of the loop.

I have founded a way (but not yet extensively tested) by doing this :

case eTypeAction.DropBomb.rawValue:
    TempParam = IDTargetSprite
    ActionBuilt = SKAction.runBlock({ DropBomb(TempParam) })

where I have to have a specific TempParam for each case...

Am I missing something obvious in the use of SKAction.runBlock or block in general ?

Upvotes: 1

Views: 347

Answers (1)

Jonah Begood
Jonah Begood

Reputation: 317

Found a quick way by passing constant instead of variable as parameters. So it works if I do like this :

case eTypeAction.DropStar.rawValue:
    let dParamsAction = LoadParamsAction()
    ActionBuilt = SKAction.runBlock({ DropStar(IDTargetSprite, dParamsAction) })

Upvotes: 1

Related Questions