如何从 GameViewController 中的另一个 swift 文件调用方法?

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

我在故事板中创建了一个按钮,它位于我的游戏屏幕上。它在 GameViewController() 中有一个 IB 动作,如下所示:

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

在我的 GameScene 中存在 myCustomMethod() ,它会产生敌人,但是上面的代码不能正常工作。如果我在 IBAction 中添加 println("button was pressed"),我会在控制台中打印出来,但 myCustomMethod 不会按预期执行并生成敌人。

谁能帮助我或解释如何解决我的问题?谢谢

在您的方法中,您每次都创建一个新的 GameScene 对象。您应该只创建一次(在初始化时),然后始终在此对象上调用 myCustomMethod

var gameScene: GameScene!

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

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