为什么我会:
致命错误:在解包可选值时意外发现nil
切换到下一个场景并回来?
// Main Menu Scene
class MainMenuScene: SKScene {
override func didMoveToView(view: SKView) {
// self.backgroundColor = UIColor.whiteColor()
var timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "switchScene", userInfo: nil, repeats: true)
println("loaded MainMenuScene")
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
}
}
func switchScene() {
println("switching to GameScene")
var game = GameScene(size: CGSizeMake(2048, 1536))
game.scaleMode = .AspectFill
if self.view == nil {
println("no self.view")
} else {
self.view!.presentScene(game)
}
}
}
// Game Scene
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
// self.backgroundColor = UIColor.whiteColor()
var timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "switchScene", userInfo: nil, repeats: true)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
}
}
func switchScene() {
// make var a member variable or this won't work
timer.invalidate()
var menu = MainMenuScene(size: CGSizeMake(2048, 1536))
menu.scaleMode = .AspectFill
self.view!.presentScene(menu)
}
}
首先,将计时器变量更改为成员。 其次,使计时器无效。
一切都按预期运行。
答案 0 :(得分:1)
来自SKScene
文档:
要呈现场景,请在SKView类上调用
presentScene:
方法或presentScene:transition:
方法。如果当前未显示场景,则此属性保留nil
。
view
为nil
,因为此代码运行时,您的GameScene
(self
)当前未显示。你的应用程序崩溃是因为你强行打开了nil
的内容。
答案 1 :(得分:0)
实际上,亚伦是对的。如果你把删除计时器,或没有添加足够的时间,那么视图将是零。在这种情况下,使用计时器,通过定时器触发的时间,视图最初具有视图。
我在忘记做的事情是在展示新的SKScene之前使我的计时器无效。这使计时器保持运行,当它触发时,查看!实际上是零,因为对象已被删除。