Search code examples
swiftskscene

How do I call a function from another scene?


My game unlocks a level every-time they beat a level. So the problem im having is when the user beats level one I want it to show a button of level 2 thats in my GameScene. When I call the function unlockLevelTwo() in my Level1.swift file it doesn't show up in my GameScene.swift file. What am I doing wrong?

//GameScene.Swift

func unlockLevelTwo() {

    let fadeIn = SKAction.fadeInWithDuration(0.5)

    levelTwo.position = CGPointMake(self.size.width / 2.0, self.size.height / 2.2)
    levelTwo.zPosition = 20
    levelTwo.setScale(0.8)
    levelTwo.alpha = 0
    levelTwo.runAction(fadeIn)
    levelTwo.name = "leveltwo"
    addChild(levelTwo)
}


//Level1.swift

    if firstBody.categoryBitMask == HeroCategory && sixthBody.categoryBitMask == GoldKeyCategory{

       //calling this function from my gameScene to unlock levelTwo button.

        var gameScene = GameScene()
        gameScene.unlockLevelTwo()

    }

Solution

  • This function:

    if firstBody.categoryBitMask == HeroCategory && sixthBody.categoryBitMask == GoldKeyCategory{
    
           //calling this function from my gameScene to unlock levelTwo button.
    
            var gameScene = GameScene()
            gameScene.unlockLevelTwo()
    
        }
    

    is creating a new GameScene object and adding the childNode "levelTwo" to that gamescene. Instead, you need to call unlockLevelTwo() on the actual GameScene that is currently presented to the user.

    I imagine somewhere in Level1.Swift there is a reference to the current GameScene (the one the user is interacting with)? Call the function on that one.

    EDIT:

    In essence, what you must do is keep a reference to your original GameScene object somewhere in your code, which I will henceforth refer to it as MyScene. That way, when in Level1.swift, you can reference MyScene and add buttons, levels, whatever you like to it without creating a new one like you did here:

    var gameScene = GameScene() gameScene.unlockLevelTwo()

    Instead, you would just call

    MyScene.unlockLevelTwo().

    If Level1 is a view of some sort, or an object that gets created, in the init function you could pass in your GameScene object and set it like so

    class Level1 : (Type) {
        var myScene: GameScene!
    
        init(myScene: GameScene) {
            self.myScene = myScene)
        }
    }
    

    Something like that, hope it helps!