ios – 无法使用Xcode 8和Swift 3以编程方式在SpriteKit中触发segue

我正在使用SpriteKit在 Xcode 8中制作游戏,并且在编程上触发segue时非常困难.我已经进入“Main.storyboard”并在我的“GameViewController”和“MenuViewController”之间创建了一个segue,因为它标识符为“toMenu”.

尝试失败#1

在我的GameScene.swift文件中,我将以下代码添加到更新功能中.

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered

    if gameIsRunning == false{
        score = 0
        performSegue(withIdentifier: "toMenu",sender: self)
    }
    }

我的目标是每当gameIsRunning为false时触发segue.但是,我收到以下错误

Use of unresolved identifier 'performSegue'

这很奇怪,因为performSegue是根据API Reference的声明.

尝试失败#2

我通过将以下代码放入“GameScene.swift”尝试了this solution

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered

    if gameIsRunning == false{
        score = 0
        GameScene(MenuViewController,animated: true,completion: nil)
    }

我收到了这个错误

Type of expression is ambiguous without more context

尝试失败#3

我发现this solution非常令人困惑,但我还是继续跟进.我已经完成了第1步,所以如第2步所述,我将以下代码放在“GameViewController.swift”的底部

func goToDifferentView() {

self.performSegue(withIdentifier: "toMenu",sender: self)

}

并没有得到错误!然后我按照解决方案的第3步中的说明将此代码添加到“GameViewController.swift”

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addobserver(self,selector: #selector(goToDifferentView),name: NSNotification.Name(rawValue: "toMenu"),object: nil)

然后我做了解决方案的第4步,所以我将以下代码放入“MenuViewController.swift”

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.post(NSNotification(name: NSNotification.Name(rawValue: "toMenu"),object: nil) as Notification)

然后我将以下代码放入我的“GameScene.swift”文件中以实际调用函数.

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered

    if gameIsRunning == false{
        score = 0
        GameViewController().goToDifferentView()
    }

然后我在我的iPhone上运行我的游戏,一切顺利,直到我到达游戏的部分,其中gameIsRunning变为假.而不是segue做它的事情,我得到以下错误

Thread 1: Signal SIGABRT

我已经多次得到这个错误,而且我总是在“Main.storyboard”中错误地连接了一些东西.然而,这是一个非常简单的游戏,一切看起来都很正常.在添加我刚刚向您展示的代码之前,我也没有收到此错误.我已多次确认segue具有标识符“toMenu”.我完全不知道为什么segue不能工作以及为什么我的Attemp#3导致SIGABRT错误.

解决方法

因为你试图在update()函数中触发这个segue,所以它每秒被调用很多次.尝试以下代码,它应该工作.
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered

if gameIsRunning == false{
    score = 0
    gameIsRunning = true
   NotificationCenter.default.post(NSNotification(name: NSNotification.Name(rawValue: "toMenu"),object: nil) as Notification)
}

如果您在if语句中放置print(“update”),您会看到我的意思.在你的if中将gameIsRunning bool设置为true将确保它只被调用一次.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...