我首先创建了GameScene并且它正常工作,现在我尝试添加MainMenu场景,除了当我点击按钮(精灵)开始游戏时,它也能正常工作,然后我得到上面的错误。
GameViewController只是库存苹果代码,它启动了MainMenu场景的应用程序,但我已经测试了在GameViewController中运行GameScene的应用程序而且我没有收到任何错误但是我没有我没有mainMenu
在GameScene中:
var UpperLeft = SKSpriteNode()
var BottomRight = SKSpriteNode()
var UpperRight = SKSpriteNode()
var BottomLeft = SKSpriteNode()
var Ball = SKSpriteNode()
错误在于每个人都强迫解开↓
override func didMove(to view: SKView) {
scoreLabel = self.childNode(withName:"scoreLabel") as! SKLabelNode
UpperLeft = self.childNode(withName:"UpperLeft") as! SKSpriteNode
BottomRight = self.childNode(withName:"BottomRight") as! SKSpriteNode
UpperRight = self.childNode(withName:"UpperRight") as! SKSpriteNode
BottomLeft = self.childNode(withName:"BottomLeft") as! SKSpriteNode
Ball = self.childNode(withName:"Ball") as! SKSpriteNode
错误在于每个人都强迫解开↑
在MainMenu中:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if let location = touches.first?.location(in: self) {
let touchedNode = atPoint(location)
if touchedNode.name == "StartGame" {
let transition = SKTransition.reveal(with: .down, duration: 1.0)
let nextScene = GameScene(size: scene!.size)
nextScene.scaleMode = .aspectFill
scene?.view?.presentScene(nextScene, transition: transition)
}
}
}
在GameViewController中:
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "mainMenu") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
view.ignoresSiblingOrder = true
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
我明白错误来自as!强迫解包,但我不知道如何从mainMenu场景调用GameScene会导致这个问题?因为我确实为每个解包创建了一个对象所以它们不应该是nil?
答案 0 :(得分:2)
问题在于您初始化GameScene
使用以下代码:
let nextScene = GameScene(fileNamed: "GameScene")
而不是MainMenu中使用的那个:
let nextScene = GameScene(size: scene!.size)
当你使用size来初始化一个场景时,它无法识别场景的.sks文件,因此在.sks文件中定义的所有节点都变为nil,这就是你在解包时遇到错误的原因。