Switch between SKScene and UIViewControllers without memory rising - ios

I have 3 UIViewControllers. The first controller - Menu Game. The second - Game. The third - Game Over controller.
In the second controller I have SKView with one scene of my game.
I created segue in storyboard between the button (Start Game) in 1-st controller and 2-nd controller. And segue between 3-rd controller (tap gesture) and 1-st controller. All segues are "Show".
In 2-nd controller I create follow:
override func viewDidLoad() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "showGameOverViewController", name: "showGameOverViewController", object: nil)
}
func showGameOverViewController() -> Void {
performSegueWithIdentifier("gameOverSegue", sender: nil)
}
Then when I need to switch from scene (in GameScene.swift) to 3-rd controller I call follow:
self.view?.presentScene(nil)
NSNotificationCenter.defaultCenter().postNotificationName("showGameOverViewController", object: nil)
This way works, but works bad.. When I tap the button in 1-st controller the 2-nd controller then follow method is calling and the scene is initialising:
override func viewDidLoad() {
let skView = self.view as SKView
if skView.scene == nil {
let gameScene = GameScene(size: skView.bounds.size)
gameScene.scaleMode = .AspectFill
skView.presentScene(gameScene)
}
}
So I have a problem. When I finish my game, go to 1-st controller again and tap Start Game button then memory of my application is rising!
And when I go from Scene to 3-rd controller then the memory of my app is rising. The rise of memory happens again and again.
I chose this way because my SKS editor doesn't works and I decided not to create Menu Scene and Game Over Scene programmatically. I thought to create Menu in Interface Builder would be better and faster and I had decided to try go this way. And I'm interested in the answer to solve my problem.
Please help me.. How to switch between SKScene and UIViewControllers without memory rising?

Related

how to keep variables and sprite kit scene in view controller

I'm trying to make app with slide menu to switch between view controllers .
Opening of the view controller is done by this code :
let destViewController : UIViewController = self.storyboard!.instantiateViewController(withIdentifier: strIdentifier)
let topViewController : UIViewController = self.navigationController!.topViewController!
if (topViewController.restorationIdentifier! == destViewController.restorationIdentifier!) {
print("Same VC")
} else {
self.navigationController!.pushViewController(destViewController, animated: true)
}
one of the view controllers contains SKview with skscene presented. However, when I open this view controller after switching to another , the sprite kit scene is not shown (the sound in it continues to play), so that it creates another skscene.
Is there any way to keep all variables/spritekit scenes during switching between view controllers ?

Unable to segue from Spritekit SKScene to another UIViewController, XCODE8/Swift

I'm completely stuck at trying to perform a segue out of the 5th and final scene of my SpriteKit game to another View Controller in the project(not the GameViewController, nor the root view controller).
I tried running self.view!.window!.rootViewController!.performSegueWithIdentifier("finalSegue", sender: self), from my finalScene, but it literally does nothing (the line gets triggered, it reads the right ViewController - i check by "print(self.view!.window!.rootViewController!)" console prints "segue read" as I instructed it, right after the segue command, as a check, the segue identifier is correct, but nothing happens).
Have tried calling a method that performs the segue from the GameViewController ( the view controller from which I am launching the view of the 5 SKScenes), I get "unexpectedly found nil while unwrapping an optional value". Tried performing the segue from the final scene ("finalScene.swift"), same error.
Have tried everything and all relevant solutions in other questions in the forum, as well as all combinations of nil/self/viewController in the "sender:" field of the performSegue method, to no avail. Here is the code that I am trying to make work which gives "unexpectedly found nil while unwrapping an optional value", pointing at the viewController var, but giving uncomprehensible debugging when loaded both on the device and on the simulator. It seems "nil" passes into the viewController var I am declaring, instead of the original GameViewController?
All my segue identifiers are correct in Storyboard, everything checked multiple times...What am I doing wrong? Should I do something different, given its the 5th SKScene and not the 1st (as in other solutions)? The segue into the SKScenes by segueing into the GameViewController from another UIViewController works fine - its the exit out of them that does not work. Many thanks for any help, completely stuck here!
Here is my relevant code:
In my GameViewController (UIViewController that launches my 5 consecutive SKScenes):
class GameViewController: UIViewController {
let myScene = finalScene()
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
//this is the 1st out of 5 SKScenes in the project
let scene = GameScene(size: CGSize(width: 2048, height: 2742))
//this is the 5th out of 5 scenes, that I am trying to trigger the segue out of
myScene.viewController = self
view.presentScene(scene)
view.ignoresSiblingOrder = true
}
}
}
Im my 5th scene, finalScene:
class finalScene: SKScene {
var viewController: GameViewController!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches{
let positionOfTouch = touch.location(in: self)
let tappedNode = atPoint(positionOfTouch)
let nameOfTappedNode = tappedNode.name
if nameOfTappedNode == "continue" {
self.viewController.performSegue(withIdentifier: "finalSegue", sender: self)
}
}
}
Just for anyone who might come across this, I solved it by using notification center. Ie added a notification observer on the parent view controller of the game scenes (which calls a function that performs the segue), and at the end point in the game where I wanted to do the segue, I posted to that notification, and it works great.
adding observer in ViewDidLoad of UIViewController:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(GameViewController.doaSegue), name: NSNotification.Name(rawValue: "doaSegue"), object: nil)
}
func doaSegue(){
performSegue(withIdentifier: "toNext", sender: self)
self.view.removeFromSuperview()
self.view = nil
}
And then calling it from within the game SKScene:
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "doaSegue"), object: nil)
You are calling the segue on the root viewController. I think that is the problem. You need to call the segue on the scene's viewController instead (where I am assuming you have created the segue, hence it is not being found on the root viewController).
Now the problem is that an SKScene does not have direct access to it's viewController, but just the view in which it is contained. You need to create a pointer to it manually. This can be done by creating a property for the SKScene:
class GameScene: SKScene {
var viewController: UIViewController?
...
}
Then, in the viewController class, just before skView.presentScene(scene)
scene.viewController = self
Now, you can access the viewController directly. Simply call the segue on this viewController:
func returnToMainMenu(){
self.viewController.performSegueWithIdentifier("menu", sender: vc)
}
Found this method to work just as well. But I do prefer the method mentioned above since it's fewer lines. I do wonder which is better for performance...

(Swift2 SpriteKit) How to transition between an SKScene and a UIViewController efficiently?

There seems to be so many contradicting ideas on this topic.
I simply wish to have my menu in a UIViewController and my game in the SKScene
In my SKScene I used:
self.removeFromParent()
self.view?.presentScene(nil)
The nodes are removed but the scene is still in place as I still have the grey background and fps counter. Can I return to the View aspect of the UIViewController and hide the scene?
My method one implementation:
RootViewController:
class RootViewController: UIViewController {
var menu = MenuViewController()
var game = GameViewController()
override func viewDidLoad() {
super.viewDidLoad()
print("root")
MenuPresent()
}
func GamePresent() {
self.addChildViewController(game)
self.view.addSubview((game.view)!)
game.didMoveToParentViewController(self)
}
func MenuPresent() {
self.addChildViewController(menu)
self.view.addSubview((menu.view)!)
menu.didMoveToParentViewController(self)
}
func menuDismiss() {
menu.willMoveToParentViewController(nil)
menu.removeFromParentViewController()
menu.view.removeFromSuperview()
}
}
MenuViewController:
class MenuViewController: UIViewController {
//var root = RootViewController()
override func viewDidLoad() {
super.viewDidLoad()
print("menu")
}
}
The print("menu") appears in my console, But the actual view and all assets of the MenuViewController do no appear.
On the other hand my GameViewController and it's SKScene work fine.
Views and scenes are two different things. Scenes are held inside of a view. You would have to simply present a scene within your menu view or transition to another view and present an SKScene from there. The code to present the scene might look like this:
let scene = GameScene(fileNamed: "GameScene")
let skView = self.view as! SKView
scene?.scaleMode = .AspectFit
skView.presentScene(scene)
First you need to know that SKScene and UIViewController are totally two different things. The hierarchy is typically as following:
UIViewController --> UIView(SKView) --> SKScene
So you SKScene is presented in a SKView which can be a UIView, then the UIView is presented in a UIViewController.
Once you know the hierarchy, everything is easy. There are many ways to use different UIViewController for menu and GameScene stuff.
Method One
For example, you can have a RootViewController, a GameViewController and a MenuViewController. The RootViewController is the initial ViewController when the app launches.
In the RootViewController, you can create a function to present the GameViewController:
func setupGameViewController() {
self.gameViewController = GameViewController()
self.addChildViewController(gameViewController!)
self.view.addSubview((gameViewController!.view)!)
gameViewController?.didMoveToParentViewController(self)
}
You need to present you SKScene in GameViewController, I guess you should be familiar with this step.
Then when you need to display the menu, you can add the MenuViewController to RootViewController with a function like:
func setupMenuViewController() {
self.menuViewController = MenuViewController()
self.addChildViewController(menuViewController!)
self.view.addSubview((menuViewController!.view)!)
menuViewController?.didMoveToParentViewController(self)
}
You also need to present you menuView in this ViewController, which I suppose you already know.
Also create a function to dismiss the MenuViewController:
func removeMenuViewController(){
self.menuViewController?.willMoveToParentViewController(nil)
self.menuViewController?.removeFromParentViewController()
self.menuViewController?.view.removeFromSuperview()
}
And everything is done.
Method Two
You can also have only one UIViewController, but create you menu as a UIView, then you can use self.view.addSuview(menuView) to present your menu. Of course you root view, which is the self.view as SKView is still there, but it doesn't matter because it's hidden behind the menuView.
A Note for your updated question
You cannot remove the scene because the scene is actually self.view as SKView, self.view is the root view of a UIViewController, it cannot be removed. If you really want to remove you scene (for most cases, it's not necessary), you can create a new SKView that present your SKScene, then add this SKView to your UIViewController by self.view.addSubview(skView), when you want to completely remove the scene, just use skView.removeFromSuperview().

Am I loading ViewController over ViewController

Hi I have a spriteKit game set up where everytime the user dies Ill get a pop up ViewController with Try again button and some iAds set up.
I have a segue to the viewController and an unwind segue from the VC to the gameViewController.
When I call the unwind func I reinitialize the scene for different reasons. My question is, am I creating view over view which will eventually lead to a crash or am I correctly reinitializing the scene. I took the code from viewDidLoad and put it into a function called "setUp()" and I call that function from the unwindSegue.
check it out: (all in GameViewController)
var currentLevel: Int!
var gameScene = GameScene()
override func viewDidLoad() {
super.viewDidLoad()
currentLevel = gameScene.currentLevel
setUp()
}
#IBAction func perpareForUnwind(unwindSegue: UIStoryboardSegue) {
setUp()
}
func setUp() {
if let scene = GameScene.level(currentLevel) {
// Configure the view.
let skView = self.view as SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
scene.viewController = self
}
}
You are not creating a new view controller if you are using the unwind segue correctly. From what it looks like that is the case. If you are still not confident you can log out println(\(self)) and make sure of it (My swift is rusty but I think that is how you log it out).
Your question title asks about view controllers but your question info asks about creating additional views. This isn't an issue either. When you do
let skView = self.view as SKView
You are getting the current view of the view controller and just casting it as an SKView. You are not recreating another view at all.
Hopefully that helps.

how to unwind from SkView

Hi I have a segues from the main menu UIViewController to start playing the game I created. But if i want to exit back to main menu there is no prepareForSegue function in SpriteKit.
How can I unwind back to the main menu from my scene?
I am using touches began to handle events instead of UIButtons
You have call performSegue from the ViewController containing the SKView not the SKScene. Create a weak variable inside SKScene pointing to the GameViewController. Set it when the SKScene is created. Then call performSegue on this property.
//Game Scene
class GameScene {
weak var gameViewController : GameViewController?
}
// GameViewController
override func viewDidLoad() {
//Other code
scene.gameViewController = self
skView.presentScene(scene)
}
When you want to perform the segue inside GameScene, call
// Inside GameScene
self.gameViewController?.performSegueWithIdentifier("indentifer", sender: self)
To go back the the main view.
self.gameViewController?.navigationController?.popViewControllerAnimated(true)

Resources