2015-07-06 50 views
0

我一直有訪問其他類的變量的問題。這是我的代碼。 這是我正在嘗試訪問變量「lastSelection」的類,它也是第一個要求查看的SKScene。如何訪問Swift中另一個SKScene的變量SpriteKit

class FighterPlaneselect : SKScene { 
    var lastSelection:String = "" 

    override func didMoveToView(view: SKView) { 
     if(true) { 
      lastSelection = "Mustang" 
     } 
    } 
} 
//Here is the second class called "GameField" 
class GameField : SKScene { 
    var FighterPlane : FighterPlaneSelect! 
    override func didMoveToView(view: SKView) { 
     FighterPlane = FighterPlaneSelect() 
     print(FighterPlane.lastSelection) 
    } 
} 

每當它打印出來它打印「」。它應該印刷「野馬」。

回答

0

在此行中:

FighterPlane = FighterPlaneSelect()

您實例化類的 SKScene。問題是,它永遠不會顯示,所以方法:func didMoveToView(view: SKView)永遠不會被調用。

你需要的是對其他場景的引用。

一種可能性是做到以下幾點:

class FighterPlaneSelect : SKScene { 
var lastSelection:String = "" 

override func didMoveToView(view: SKView) { 
     if(true) { 
      lastSelection = "Mustang" 
     } 
    } 
} 

//Here is the second class called "GameField" 
class GameField : SKScene { 
    var fighterPlane : FighterPlaneSelect! 
    override func didMoveToView(view: SKView) { 
     print(FighterPlane.lastSelection) 
    } 
} 

//Here is in the GameScene 
let fighterPlaneSelect = FighterPlaneSelect 
//show the scene to make it move to view 
//then assign the variable inside the gameField object 
let gameField = GameField() 
gameField.fighterPlane = fighterPlaneSelect 
+0

的FighterPlaneSelect視圖首先被調用,則GameField視圖 –

+0

從哪個類被稱爲它們? – Tokuriku

+0

這實際上並不是我的完整代碼,因爲我不想展示它。 FighterPlaneSelect類是有史以來的第一個視圖。它被稱爲GameScene,但我想出瞭如何改變它。所以這是默認視圖 –

0

可以初始化變量在現場的init方法:

class FighterPlaneselect : SKScene { 
    var lastSelection:String = "" 

    override init(size: CGSize){ 

     super.init(size: size) 

     lastSelection = "Mustang" 

    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    override func didMoveToView(view: SKView) { 

    } 
} 

,然後只用它爲你做的已經:

class GameField : SKScene { 
    var FighterPlane : FighterPlaneselect! 

    override func didMoveToView(view: SKView) { 


     FighterPlane = FighterPlaneselect(size: self.size) 

     println(FighterPlane.lastSelection) 
    } 
} 
0

非常簡單!只需在課堂外聲明lastSelection!

class FighterPlaneselect : SKScene { 
var lastSelection:String = "" //Declared in the class 
} 

var lastSelection:String = "" //Declared outside the class 
class FighterPlaneselect : SKScene { 

} 
相關問題