How do i pass a variable from GameController:UIController to SKScene in swift?

Output:

[MC] Reading from private effective user settings.
Simulator user has requested new graphics quality: 100
scene did load
userData nil
userData nil
userData nil
try to set username
setting username
userData nil
playername in scene nil
userdata in scene nil
userdata in scene nil
userData nil
playername Optional("jsky")
playername in controller Optional(jsky)
scene did load
userData nil
userData nil
userData nil
try to set username
setting username
userData nil
playername in scene nil
userdata in scene nil
userdata in scene nil
userData nil
controller: the scenes root node: Optional(<SKScene> name:'(null)' frame:{{-375, -667}, {750, 1334}} anchor:{0.5, 0.5})
scene called didMove
userData nil

GameViewController Class

class GameViewController: UIViewController {

    var playername:String?
    var scene: GKScene?

    override func viewDidLoad() {
            super.viewDidLoad()

            if let view = self.view as! SKView? {

            if let scene = GKScene(fileNamed: "GameScene") {

                // Get the SKScene from the loaded GKScene
                if let sceneNode = scene.rootNode as! GameScene? {

                    // Copy gameplay related content over to the scene
                    sceneNode.entities = scene.entities
                    sceneNode.graphs = scene.graphs


                    print("playername", self.playername)
                    var userDataDict: NSMutableDictionary = [:] //init dict,  nil by default
                    sceneNode.userData = userDataDict
                    sceneNode.userData?.setObject(self.playername!, forKey: "playername" as NSCopying)
                    print("playername in controller", sceneNode.userData?["playername"])

                    // Set the scale mode to scale to fit the window
                    sceneNode.scaleMode = .aspectFill
                    let scene = GKScene(fileNamed: "GameScene", rootNode: sceneNode)
                    self.scene = scene

                    // Present the scene
    //                if let view = self.view as! SKView? {
                    print("controller: the scenes root node:", self.scene!.rootNode)
                        view.presentScene(self.scene?.rootNode as! SKScene)
    //                    view.isAsynchronous=false
                        view.ignoresSiblingOrder = true
                        view.showsFPS = true
                        view.showsNodeCount = true
    //                    view.scene.setUsername()
    //                    view.scene?.didMove(to: view)
                    }
                }
            }
        }
}

GameScene Class

import SpriteKit
import GameplayKit

    class GameScene: SKScene {

        var entities = [GKEntity]()
        var graphs = [String : GKGraph]()
        var playername: String?

        private var lastUpdateTime : TimeInterval = 0
        private var label : SKLabelNode?
        private var usernamelabel : SKLabelNode?
        private var spinnyNode : SKShapeNode?



        override func sceneDidLoad(){
            print("scene did load")
            print("userData",self.userData)
            print("userData",self.userData)

            self.lastUpdateTime = 0


            // Get label node from scene and store it for use later
            self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode
            if let label = self.label {
                label.alpha = 0.0
                label.run(SKAction.fadeIn(withDuration: 2.0))
                label.text = "test"
            }

            // Create shape node to use during mouse interaction
            let w = (self.size.width + self.size.height) * 0.05
            self.spinnyNode = SKShapeNode.init(rectOf: CGSize.init(width: w, height: w), cornerRadius: w * 0.3)

            if let spinnyNode = self.spinnyNode {
                spinnyNode.lineWidth = 2.5

                spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1)))
                spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5),
                                                  SKAction.fadeOut(withDuration: 0.5),
                                                  SKAction.removeFromParent()]))
            }

            print("userData",userData)
            do{
            print("try to set username")
            try
                setUsername()
            }
            catch{
                print("no username set")
            }

        }

        func setUsername() throws {

            print("setting username")
            print("userData",self.userData)

            self.usernamelabel = self.childNode(withName: "//usernamelabel") as? SKLabelNode
            do{


            if let usernamelabel = self.usernamelabel{
            usernamelabel.alpha = 0.0
            usernamelabel.run(SKAction.fadeIn(withDuration: 2.0))

                print("playername in scene", self.playername)
                print("userdata in scene", self.parent?.userData)
                print("userdata in scene", self.userData)
            }
            print("userData",self.userData)
            if let playername: String = userData?.value(forKey:"playername") as? String{
            print("playername from userdata is", playername)
            usernamelabel?.text=playername

            }

            }catch {

                throw GameError.PlayerNameNotFound
            }
        }

        override func didMove(to view: SKView){
            print("scene called didMove")
            print(self.userData)
            if let playername = self.userData?.value(forKey: "playername") {
                print("gameInfo is :\(playername)")
                do{ try self.setUsername()}
                catch{
    //                throw.GameError.PlayerNameNotFound
                    print("couldnt set username")
                }
            }
        }
    }

0 Answers