问题
I created a menu in Storyboard that passes some information through a segue to GameViewController. Ideally, I could use that segue to pass the information directly to GameScene.swift where I need it, but I'm not sure that's an option since a scene is just a view and not a view controller. So, I pass the information to the GameViewController and that works great. But now, how to I get it to GameScene.swift?
Segue from menu to GameViewController
func passToGame(game: String) {
performSegue(withIdentifier: "toGameSegue", sender: game)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationVC = segue.destination as? GameViewController {
if let item = sender as? String {
destinationVC.gameInfo = item
}
}
}
GameViewController
class GameViewController: UIViewController {
var gameInfo: String? //This works great - now how do I get it to GameScene.swift?
override func viewDidLoad() {
super.viewDidLoad()
...
回答1:
As the others SKNode
, SKScene
have an istance property called userData, you could use this dictionary to store whatever you want before to present the scene (this example come from the "Hello World" Sprite-kit template):
class GameViewController: UIViewController {
var gameInfo: String?
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
scene.userData = NSMutableDictionary()
scene.userData?.setObject(gameInfo ?? "", forKey: "gameInfo" as NSCopying)
view.presentScene(scene)
}
...
To retrieve the value from the GameScene
you can simply do:
override func didMove(to view: SKView) {
if let gameInfo = self.userData?.value(forKey: "gameInfo") {
print("gameInfo is :\(gameInfo)")
}
...
来源:https://stackoverflow.com/questions/43239709/spritekit-passing-variable-from-gameviewcontroller-to-gamescene