SpriteKit: Passing variable from GameViewController to GameScene

孤街浪徒 提交于 2019-12-06 09:36:14

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