简体   繁体   English

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

[英]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: 它在GameViewController()中具有IB动作,如下所示:

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

In my GameScene lives myCustomMethod() which will spawn enemies, however the code above doesn't work properly. 在我的GameScene中,存在myCustomMethod(),它将生成敌人,但是上面的代码无法正常工作。 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. 如果在IBAction中添加println("button was pressed") ,则会在控制台中将其打印出来,但是myCustomMethod将不会执行,并且不会按预期方式产生敌人。

Can anyone help me or explain how to resolve my issue? 谁能帮助我或解释如何解决我的问题? Thanks 谢谢

In your method, you create a new GameScene object each time. 在您的方法中,您每次都会创建一个新的GameScene对象。 You should only create it once (at initialization), and then always call myCustomMethod on this object. 您仅应创建一次(初始化时),然后始终在此对象上调用myCustomMethod

var gameScene: GameScene!

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM