Alex Merlin
Alex Merlin

Reputation: 451

How can I use a string as a name for the SKScene

I am making game with 24 levels and I am using NSUserDefaults to let me know what level I am in by setting its value to the level number.

I am trying to get the NSUserDefault value and set it as a string so that when I present the scene it will know what level to go to. But for some reason it is not working. It says I cannot convert a string to an SKScene.

The userdefault saves the number level (1,2,3,etc). With that number I want to go to that scene, which are named (Level1, Level2, etc.) I am trying to attach the number to the string "Level%i" and then present the scene using that string. But it is not letting me it says cannot convert String to SKScene.

Here is the code used to present the level scene:

if self.atPoint(location) == NextLevelButton{

        let LevelSelection = UserDefaults.standard.object(forKey: "LevelSelection") //as? String




        let level2 = NSString(format: "Level%@", LevelSelection! as! SKScene) // Here is where I try to make a string and convert it into a SKScene

        removeAllActions()
        removeAllChildren()
        let scene = level2 (size: self.size) // I get an error here   "Cannot call value of non-function type 'NSString'"
        let sKView = self.view! as SKView
        sKView.ignoresSiblingOrder = true
        scene.scaleMode = .aspectFill

        sKView.presentScene(scene)

Here is the other part of the code in the Level1 scene:

let defaultLevel = 1
UserDefaults.standard.set(defaultLevel, forKey: "LevelSelection")

The Scene's name is Level1, Level2, etc. I just need to append the number of the NSUserDefualt variable to the string "Level" and I have the scene

Does anyone know what am I doing wrong? And if this is not the correct way to do it, What is?

Thank You In Advance !

Upvotes: 0

Views: 113

Answers (1)

vadian
vadian

Reputation: 285280

You can't do that. A string is not convertible to an object.

A possible solution is an array:

let levels : [SKScene] = [level1, level2, level3]

Then you can retrieve the level by index

let levelSelection = UserDefaults.standard.integer(forKey: "LevelSelection")
let scene = levels[levelSelection - 1]

Upvotes: 1

Related Questions