我的问题很简单:如何在GameScene
上打印GameViewController
的变量?
我在下面创建了这段代码,因此更容易理解。
GameScene.swift
import SpriteKit
class GameScene: SKScene {
var variable = Int()
override func didMoveToView(view: SKView) {
/* Setup your scene here */
variable = 50
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
NSNotificationCenter.defaultCenter().postNotificationName("calledFromGameSceneVC", object: nil)
}
}
GameViewController.swift
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Set view size.
let scene = GameScene(size: view.bounds.size)
// Configure the view.
let skView = view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .ResizeFill
skView.presentScene(scene)
//------------------------------//
//Register observer
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GameViewController.calledFromGameScene), name: "calledFromGameSceneVC", object: nil)
}
func calledFromGameScene(){
//Print variable
let scene = GameScene(size: view.bounds.size)
print("My variable from GameScene is: ", scene.variable)
}
}
对不起,简要说明。
提前致谢,
路易斯。
答案 0 :(得分:2)
您尝试实现的对象间通信类型可能最好通过使用协议的委派模式来解决:
<强> GameScene.swift 强>
import SpriteKit
protocol GameSceneDelegate {
func calledFromGameScene(scene: GameScene)
}
class GameScene: SKScene {
var variable = Int()
var gameDelegate: GameSceneDelegate?
override func didMoveToView(view: SKView) {
/* Setup your scene here */
variable = 50
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
gameDelegate?.calledFromGameScene(self)
}
}
<强> GameViewController.swift 强>
class GameViewController: UIViewController, GameSceneDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Set view size.
let scene = GameScene(size: view.bounds.size)
// Configure the view.
let skView = view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .ResizeFill
/* Set the delegate */
scene.gameDelegate = self
skView.presentScene(scene)
}
func calledFromGameScene(scene:GameScene){
//Print variable
print("My variable from GameScene is: ", scene.variable)
}
}
请注意,您不能在delegate
上使用属性名称GameScene
,因为SKScene
已经拥有delegate
属性