I have an SKLabel attached to a parent SKNode and an array of strings:
let configText:[String] = [
"Configuration",
"Do stuff",
"Do more stuff",
"Nil",
"It is the void"]
The array is looped through with the following:
parentNode_Label.run(
SKAction.sequence([
SKAction.run{
if self.counter == self.configText.count - 1
{ self.counter = 0 } },
SKAction.wait(forDuration: 3.0),
SKAction.run { self.sprite_Label.text = self.configText[self.counter + 1] },
SKAction.fadeIn(withDuration: 0.5),
SKAction.wait(forDuration: 3.0),
SKAction.fadeOut(withDuration: 0.5),
SKAction.run{ self.counter += 1 }
]).forever()
)
extension SKAction
public func forever() -> SKAction { return SKAction.repeatForever( self ) }
}
It works but seems kind of clunky/hacky. Is there a simpler, more efficient yet readable way to do this?
1 Answer 1
The first array element
configText[0]
is never used, so you can remove it from the array (and modify the index calculations accordingly).Incrementing the counter with wrap-around can be simplified using the remainder operator:
self.counter = (self.counter + 1) % self.configText.count
The three "run" actions can be combined into one.
Inside the actions array you can refer to the
SKAction
members without specifying the type explicitly, e.g..wait
instead ofSKAction.wait
.
Putting it all together:
parentNode_Label.run(
SKAction.sequence([
.wait(forDuration: 3.0),
.run {
self.sprite_Label.text = self.configText[self.counter]
self.counter = (self.counter + 1) % self.configText.count
},
.fadeIn(withDuration: 0.5),
.wait(forDuration: 3.0),
.fadeOut(withDuration: 0.5),
]).forever()
)
Also have a look at the Swift naming conventions:
Names of types and protocols are UpperCamelCase. Everything else is lowerCamelCase.
For example: parentNode
, textLabel
, without underscores.