Swift 5, iOS 14
Wrote this code to fade in a sprite node... works ok, but Xcode says this, which makes no sense since I am using timer within the loop.
Initialization of immutable value 'timer' was never used; consider replacing with assignment to '_' or removing it
let timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { timer in
node2Delete?.alpha -= 0.1
ghost.alpha += 0.1
if node2Delete?.alpha == 0 {
node2Delete?.removeFromParent()
timer.invalidate()
}
}
And it doesn't complain about the timer within the loop not being defined? Is this a bug or am I missing something?
Is there a better way to do this? Is the timer I set here actually being cancelled?
You want to use SKAction not Timer here, so you can replace all your code with the below.
Create two variables which hold the fade logic, one for fade in, the other for fade out.
Run fadeIn
on your ghost
node. The ghost node will gradually appear over the course of 5 seconds.
Run fadeOut
on your node2Delete
node, this will gradually fade the alpha to 0 over the course of 5 seconds. Once completed, we remove the node from it's parent.
let fadeOut = SKAction.fadeAlpha(to: 0.0, duration: 5.0)
let fadeIn = SKAction.fadeAlpha(to: 1.0, duration: 5.0)
ghost.run(fadeIn)
node2Delete.run(fadeOut){
self.node2Delete.removeFromParent()
}