2017-04-02 56 views
7

我在Xcode 8中使用SpriteKit製作遊戲,並且以編程方式觸發segue時非常困難。我已經進入了「Main.storyboard」,並且在我的「GameViewController」和「MenuViewController」之間做了一個循環,因爲它的標識符是「toMenu」。無法以編程方式在SpriteKit中觸發segue,使用Xcode 8和Swift 3

失敗的嘗試#1

在我的GameScene.swift文件我已經添加以下代碼更新功能。

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

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

我的目標是讓segue在gameIsRunning爲false時觸發。但是,我得到了以下錯誤:

Use of unresolved identifier 'performSegue' 

這是奇怪,因爲performSegue是根據API Reference聲明。

失敗的嘗試#2

我通過把下面的代碼 「GameScene.swift」

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

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

試圖this solution,我得到這個錯誤:

Type of expression is ambiguous without more context 

失敗嘗試#3

我發現this solution很混亂,但我沿着反正。我已經做了第1步,從而在步驟2中指出,我把下面的代碼在「GameViewController.swift」

func goToDifferentView() { 

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

} 

的底部,並沒有得到一個錯誤!然後我說這個代碼爲「GameViewController.swift」作爲解決方案

override func viewDidLoad() { 
    super.viewDidLoad() 

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

隨後的第3步指示我沒有解決方案的步驟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錯誤。

+0

它是什麼樣的segue? – GlennRay

+0

@GlennRay這是一種'顯示(例如推)',它是一個'故事板Segue'。我不知道如何獲得關於它的任何額外的細節。 – chas

+1

偉大的第一個問題。提示:如果您想使用粗體,在一段文本的任一側使用雙星,與HTML相比,輸入更容易(並且更易於重新編輯)。如果你想在段落中設置一行內嵌的代碼,可以在任何一邊使用反引號。 – halfer

回答

2

由於您試圖在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) 
} 

如果你放置print("update")if聲明,你會明白我的意思。將gameIsRunning bool設置爲true將保證它只會被調用一次。

相關問題