Reputation: 1074
I have quite a specific problem. I used to be presenting my Game Scene from a view controller with the default code. However I Added another SKScene and am now presenting my game scene from that using this code:
//In an SKScene (not Game scene)
let scene = GameScene()
let skView = self.view!
skView.ignoresSiblingOrder = true
scene.scaleMode = .aspectFit
let push = SKTransition.push(with: SKTransitionDirection.right, duration: 0.4)
skView.presentScene(scene, transition: push)
My problem is that my game scene seems to no longer recognize my SKS file as when I run the line of code:
//in gamescene
sprite = self.childNode(withName: "sprite") as! SKLabelNode
It doesn't find anything when unwrapping. When I present my SKScene from GameViewController using the code:
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
// Set the scale mode to scale to fit the window
sceneNode.scaleMode = .aspectFit
// Present the scene
if let view = self.view as! SKView? {
view.presentScene(sceneNode)
view.ignoresSiblingOrder = true
}
}
}
Everything works. What am I doing wrong? Thanks in advance.
Upvotes: 1
Views: 321
Reputation: 2666
I think the reason that it crashes when you present from within the SKScene
, and not from the UIViewController
is because of 2 reasons.
SKScene
, you create an object of type GameScene
but when you present from the UIViewController
you create an object of type GKScene
.GameScene
, you use an initializer that does not take into account the attached SKS File. But when you create the object of type GKScene
you do.Therefore, I would edit the first block of code to be:
//In an SKScene (not Game scene)
if let sceneContainer = GKScene(fileNamed: "GameScene") {
let skView = self.view!
skView.ignoresSiblingOrder = true
//Something comparable to the following line. I don't have a project set up, but let the compiler run you through the exact syntax.
let scene = sceneContainer.rootNode as! GameScene?
scene?.scaleMode = .aspectFit
let push = SKTransition.push(with: SKTransitionDirection.right, duration: 0.4)
skView.presentScene(scene!, transition: push)
}
The doc for getting the SKScene
from a GKScene
can be found here.
Upvotes: 1