我需要将几个变量从GameViewController传递给GameScene。
GameViewController:
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(size: view.frame.size) as GameScene? {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
skView.showsPhysics = false
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
// pass game set-up variables
scene.idDefence = idDefence
scene.idAttack = idAttack
scene.tries = tries
scene.runs = runs
scene.teamShirt = teamShirt
skView.presentScene(scene)
}
}
GameScene-具有上面列出的变量(idDefence)等。
class GameScene: SKScene, SKPhysicsContactDelegate {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// variables - set-up defenders
var idDefence = 0
...
这符合要求,但idDefence变量(从GameViewController正确打印为数字的println)没有传递给活动的GameScene,而是保持为0。GameScene代码:
override init(size: CGSize) {
super.init(size: size)
physicsWorld.gravity = CGVectorMake(0.0, 0.0)
physicsWorld.contactDelegate = self
getDefenceInfo()
getAttackInfo()
loadLevel()
spawnPlayers()
spawnDefenders()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// get attack variables from database
func getDefenceInfo(){
println("defence ID: \(idDefence)")
}
任何帮助,不胜感激
最佳答案
您正在检查init(size:)
初始化程序中这些属性的值;在网上被称为:
if let scene = GameScene(size: view.frame.size) as? GameScene {
...
}
至此,尚未运行通过GameViewController设置属性值的代码。因此它们仍然具有默认值。
如果在
didMoveToView
的GameScene
方法中检查属性的值,您会看到它们都具有正确的值,因为didMoveToView
将在skView.presentScene(scene)
之后调用。关于ios - Swift:从GameViewController设置GameScene变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31257711/