我想知道如何每隔 (x) 秒从数组中获取一个随机字符串并将其显示到 SKLabelNode 中。在这种情况下,每 3 秒一次。
到目前为止,这段代码从我的数组中显示了一个随机字符串,我只需要添加一个计时器,以便每隔几秒打印一个不同的字符串。
我想要打印随机字符串的 SKLabelNode 是“colorClick”
这是数组本身:让 whichcolortoclick = ["Blue Box", "Red Box", "Pink Box", "Yellow Box"]
let randomIndex = Int(arc4random_uniform(UInt32(whichcolortoclick.count)))
colorClick.text = (whichcolortoclick[randomIndex])
总而言之,我真正想要的是添加一个计时器,并每隔几秒从数组中显示一个随机字符串。然后,将其显示在 colorClick LabelNode 中。
最佳答案
您可以为此使用 SKAction repeat forever(不要在 SpriteKit 中使用 NSTimers)。
像这样
override func didMove(to view: SKView) {
let actionUpdateLabel = SKAction.run { [weak self] in
self?.updateTextLabel()
}
let actionDelay = SKAction.wait(forDuration: 3) // swap this with the update action if you want to have the delay first.
let sequenceUpdateLabel = SKAction.sequence([actionUpdateLabel, actionDelay])
run(SKAction.repeatForever(sequenceUpdateLabel))
}
func updateTextLabel() {
let randomIndex = Int(arc4random_uniform(UInt32(whichcolortoclick.count)))
colorClick.text = (whichcolortoclick[randomIndex])
}
希望对你有帮助
关于swift - 如何每 (x) 秒从数组中获取随机字符串 (SWIFT 3)(SPRITEKIT),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42215244/