gpt4 book ai didi

swift - 其他场景调用时"unexpectedly found nil while unwrapping an Optional value"

转载 作者:行者123 更新时间:2023-11-28 12:34:44 25 4
gpt4 key购买 nike

我首先创建了 GameScene 并且它可以工作,现在我尝试添加一个 MainMenu 场景,它也可以工作,除非我按下按钮( Sprite )开始游戏,然后我得到上面的错误。

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 导致这是一个问题?因为我确实为每个解包创建了一个对象,所以它们不应该为零?

最佳答案

问题出在您初始化 GameScene 的方式上

使用以下代码:

 let nextScene = GameScene(fileNamed: "GameScene")

而不是 MainMenu 中使用的那个:

 let nextScene = GameScene(size: scene!.size)

当您使用 size 初始化场景时,它无法识别场景的 .sks 文件,因此您在 .sks 文件中定义的所有节点都变为 nil,这就是为什么在展开它们时出错。

关于swift - 其他场景调用时"unexpectedly found nil while unwrapping an Optional value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41215455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com