DanTdd
DanTdd

Reputation: 342

How can I call a method from another swift file in GameViewController?

I have a button that I have created in storyboard that lives on my game game screen. It has an IB action in GameViewController() as follows:

   @IBAction func buttonPressed(sender: AnyObject) {
        GameScene().myCustomMethod()
    }

In my GameScene lives myCustomMethod() which will spawn enemies, however the code above doesn't work properly. If I add a println("button was pressed") in the IBAction, I get that print out in the console but myCustomMethod won't execute and spawn the enemies as expected.

Can anyone help me or explain how to resolve my issue? Thanks

Upvotes: 1

Views: 426

Answers (1)

return true
return true

Reputation: 7916

In your method, you create a new GameScene object each time. You should only create it once (at initialization), and then always call myCustomMethod on this object.

var gameScene: GameScene!

override func viewDidLoad() {
    gameScene = GameScene()
}

@IBAction func buttonPressed(sender: AnyObject) {
    gameScene.myCustomMethod()
}

Upvotes: 1

Related Questions