SpriteKit: Passing variable from GameViewController to GameScene

时间秒杀一切 提交于 2020-01-02 16:18:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!