how to unwind from SkView - ios

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)

Related

SKScene stays in memory after dismissing its parent view controller

When testing my app I realised that going to the view controller which presents my scene and back again increases the used space in memory. So I run instruments to learn what wasn’t deallocated. I found that there was some instances of my scene taking up space. How can I fix it?
I have a property in my scene class to access its view controller (which I defined as weak to avoid a retain cycle)
The concerning lines in my scene class are:
weak var viewController: MyViewControllerClass?
func exitFunction () {
viewController.dismiss(animated: true , completion: nil)
self.view!.presentScene(nil)
}
All your scenes should belong to the same view controller, that is to say in a sprite kit game there is only one view controller.
You should define your scenes and the SKView to present them on in this view controller like so:
class GameViewController: UIViewController {
var skView: SKView?
var mainMenu: MainMenu?
override func viewDidLoad() {
super.viewDidLoad()
skView = self.view as! SKView?
}
Inside your scene make sure you are deallocating your resources properly:
override func willMove(from view: SKView) {
removeAllChildren()
}
deinit {
//Deallocate your resources here
}
WillMove is called each time you move from the scene to another.
Finally when you show your scenes from inside your viewController class make sure you deallocate old ones first:
func showMainMenu(_ notification: Notification) {
deallocScenes()
mainMenu = MainMenu(fileNamed: "MainMenu")
mainMenu?.scaleMode = .fill
skView!.presentScene(mainMenu)
}
func deallocScenes(){
mainMenu = nil
levelSelection = nil
credits = nil
}

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().

can't open a viewcontroller from an SKScene

I have created a game where the main menu is contained within a normal ViewController and the actual game is played within an SKScene.
I use a modal segue from a button on the main menu to open the SKScene.
The problem I get is when I try to return from the SKScene to the main menu.
I'm using this code to present the main menu
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if homeBtn.containsPoint(location)
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let settingController: UIViewController = storyboard.instantiateViewControllerWithIdentifier("homeViewController") as UIViewController
let vc = self.view?.window?.rootViewController
vc?.presentViewController(settingController, animated: true, completion: nil)
}
}
}
However this causes the following message:
Warning: Attempt to present ViewController on ViewController whose view is not in the window hiearchy!
Your Scene should not call back to the ViewController. It creates too much dependence between the View and the ViewController.
Here is how I use the delegate in Objective-C (sorry I don't know swift). Here are some examples in Swift.
// GameViewController.h
#interface GameViewController : UIViewController <GameSceneDelegate>
// GameViewController.m
// where we setup new scenes. Don't forget this.
newScene.delegate = self;
-(void)displayMenu {
... setup and display the menu
}
Create a simple delegate class
// GameSceneDelegate.m
#protocol GameSceneDelegate <NSObject>
-(void)displayMenu;
#end
Your game scene now keeps a reference to the delegate. Other ViewControllers can now use your GameScene without backward references.
// GameScene.h
#interface GameScene : SKScene
#property (assign) id<GameSceneDelegate> gameSceneController;
// GameScene.m
[self.gameSceneController displayMenu];
Other ways you can get the message back to the GameViewController is using an NSController, but this is a bit messy. Or you could also consider something like Reactive Cocoa.

Switch between SKScene and UIViewControllers without memory rising

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?

Resources