我一直遇到从其他类访问变量的问题。这是我的代码。 这是我试图访问变量" lastSelection"它也是第一个被称为观看的SKScene。
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)
}
}
每当打印出来时,它都会打印出#34;"。它应该是印刷" Mustang"。
答案 0 :(得分: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
答案 1 :(得分:0)
您可以在场景的初始化方法中初始化该变量:
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)
}
}
答案 2 :(得分:0)
非常简单!只需在课堂外声明lastSelection !!
class FighterPlaneselect : SKScene {
var lastSelection:String = "" //Declared in the class
}
var lastSelection:String = "" //Declared outside the class
class FighterPlaneselect : SKScene {
}