I know this question has been asked many times, however most aren't properly answered and do not follow the same set up as mine.
I have two UIViewControllers, GameViewController and MenuViewController. The MenuViewController uses a storyboard and UIKit. The GameViewController loads an SKScene. When the app starts it opens the MenuViewController. I have already made a button that segues to the Game on the Menu in the storybaord. That works, but now I am trying to do the opposite and return back to the Menu while in the Game. I have tried to use code that has answered similar questions but none seems to work.
Here is my GameViewController that I messed around with:
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView?{
if let scene = SKScene(fileNamed: "GameScene"){
let gameScene = scene as! GameScene
gameScene.gameViewControllerDelegate = self
gameScene.scaleMode = .aspectFill
view.presentScene(gameScene)
}
view.showsFPS = true
view.showsNodeCount = true
view.ignoresSiblingOrder = true
// Do any additional setup aft)er loading the view.
}
}
func callMethod(inputProperty:String){
print("inputProperty is: ",inputProperty)
}
And the code I added to my GameScene:
class GameScene: SKScene, SKPhysicsContactDelegate {
weak var gameViewControllerDelegate:GameViewControllerDelegate?
override func didMove(to view: SKView) {
gameViewControllerDelegate?.callMethod(inputProperty: "call game view controller method")
Related
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
}
QUESTION: How can I dismiss a ViewController from my GameScene.swift ?
SITUTATION: I have 2 VCs in my SpriteKit Game, like so:
ViewController.swift ----Press Play-----> GameViewController
When the player loses, I want to dismiss the GameViewController so the player can press play again. I check for the player's loss in my GameScene.swift and would like to dismiss the GameVC from there.
N.B.: Googled this without success.
WHAT I TRIED:
1) Creating a gameVC instance in my GameScene.swift and dismissing it like so:
let gameVC = GameViewController()
gameVC.dismissViewController(false,completion: nil)
2) Doing:
self.view.window!.rootViewController?.dismissViewControllerAnimated(false, completion: nil)
Those don't work for obvious reasons ^^
You don't want to "grab" the existing instance: https://pragprog.com/articles/tell-dont-ask
You need to either hand GameScene a reference to the view controller so it can dismiss it, or use the delegate pattern to communicate backwards to a controlling object that the VC should be dismissed/dismiss itself.
A simple example… you can add a GameViewController property to GameScene, then dismiss the VC at the appropriate time:
class GameScene: SKScene {
var gameVC: GameViewController?
func gameDidEnd() {
gameVC?.dismissViewControllerAnimated(true) {
// if desired, do any cleanup after the VC is dismissed
}
}
}
Then, just set this property when creating the GameScene object in the first place:
if let gameScene = GameScene(fileNamed: "MyScene") {
gameScene.gameVC = someGameVC
}
This simple approach will tightly couple GameScene and GameViewController, making it a bit more difficult if you ever want to use one of these objects without the other. But for this simple use case, it may be fine.
I've follow some of your discussion. I want to add some code, because usually I prefeer to work with one ViewController or two and many SKScene and SKNode, but in this case could be useful to have a currentViewController reference:
class MyModelScene: SKScene {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var currentViewController : MyModelViewController! = MyModelViewController()
// MyModelViewController is a customized UIViewController
override func didMoveToView(view: SKView) {
super.didMoveToView(view)
print("---")
print("∙ \(NSStringFromClass(self.dynamicType))")
print("---")
}
}
class Level1Scene: MyModelScene {
...
}
In the UIViewController:
class PreloadViewController: MyModelViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = Level1Scene(fileNamed:"Level1Scene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsPhysics = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .ResizeFill
scene.currentViewController = self
skView.presentScene(scene)
}
}
}
With this code , you've always a currentViewController reference in your SKScene and you can check if it's the correct viewController you want to dismiss or not.
I'm currently trying to implement IAP into my SKScene like this Swift Sprite Kit In App Purchase
but I'm having a problem figuring out how to set self.canDisplayBannerAds to false from my skscene, The code I used did nothing. Any help would be appreciated.
func removeAds() {
let viewController: GameViewController = GameViewController()
viewController.canDisplayBannerAds = false
}
The reason why your code isn't working is because you are creating a NEW GameViewController and setting canDisplayBannerAds on that.
You need to keep a reference to your original GameViewController which you should be able to access from within your scene via your scenes SKView.
If you don't want to subclass your SKView you can use the following to get your current viewController.
if let viewController = view.nextResponder as? GameViewController /* or whatever your VC is */ {
viewController.canDisplayBannerAds = false
}
If your SKView is a subview change view.nextResponder to view.superview.nextResponder.
Alternatively you can use Notification Center to send a message to your GameViewController
In your GameViewController.
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "turnOffAds", name: "TurnOffAdsNotification", object: nil)
}
func turnOffAds() {
self.canDisplayBannerAds = false
}
Somewhere in your SKScene:
NSNotificationCenter.defaultCenter().postNotificationName("TurnOffAdsNotification", object: nil)
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.
Inside my main UIViewController, I'm defining two SKScenes. I want to present only gameScene at first, and then present uiScene later, triggered by an action in gameScene (hitting the pause button).
The problem is that skView, the view containing both scenes, is not recognized outside of the UIViewController.
The code is below. Any help would be appreciated.
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let skView = view as SKView
let gameScene = GameScene(size: view.bounds.size)
gameScene.scaleMode = .ResizeFill
skView.presentScene(gameScene)
let uiScene = UIScene(size: view.bounds.size)
uiScene.scaleMode = .ResizeFill
uiScene.backgroundColor = UIColor.clearColor()
//skView.presentScene(uiScene) // I want to present this line from within gameScene.
}
}
let reveal = SKTransition.flipHorizontalWithDuration(0.5)
let scene = uiScene(size: size)
self.view?.presentScene(scene, transition:reveal)
You can transition from one scene to another from within the scene. My code is pulled from http://www.raywenderlich.com/84434/sprite-kit-swift-tutorial-beginners in the last section.
Remember to import the header of the scene you are transitioning TO in the scene you are transitioning FROM.