Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用AppDelegate、Swift在SpriteKit中暂停计时器?_Swift_Sprite Kit_Appdelegate - Fatal编程技术网

如何使用AppDelegate、Swift在SpriteKit中暂停计时器?

如何使用AppDelegate、Swift在SpriteKit中暂停计时器?,swift,sprite-kit,appdelegate,Swift,Sprite Kit,Appdelegate,我正在制作一个iPhone游戏,当游戏被中断时(例如来电),我会尝试暂停游戏。我的项目中使用了计时器,但不知道如何从AppDelegate访问它们。有什么想法吗?谢谢对我来说,有效的方法是创建一个名为Shared.Swift之类的新Swift文件,并声明我需要在其他场景中使用的任何变量和常量 因此,创建一个名为Shared.swift的文件 在共享中,将计时器的声明移到其中。您不需要将Shared声明为类或结构,以下是Shared的外观: import UIKit import Foundati

我正在制作一个iPhone游戏,当游戏被中断时(例如来电),我会尝试暂停游戏。我的项目中使用了计时器,但不知道如何从AppDelegate访问它们。有什么想法吗?谢谢

对我来说,有效的方法是创建一个名为Shared.Swift之类的新Swift文件,并声明我需要在其他场景中使用的任何变量和常量

因此,创建一个名为Shared.swift的文件

在共享中,将计时器的声明移到其中。您不需要将Shared声明为类或结构,以下是Shared的外观:

import UIKit
import Foundation
import SpriteKit

//All three aren't necessary for just a timer, but will save time later if you decide to declare other things here

//Now, MOVE the declaration of your timer here

let timer: NSTimer?

就这样,只需在AppDelegate中访问它,就像您在那里声明的那样。

这就是我在游戏中所做的。只需在GameSecene类外部而不是内部定义计时器变量

var timer = NSTimer() //Define my timer outside my gamescene class so I could access it in App Delegate

class GameScene: SKScene {



}

您可以在AppDelegate上创建一个共享的var,当调用您的NSTimer方法时,您可以在离开其以下方法之前检查该var是否有效,例如:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var isGameOver:Bool = false
    //.....
}
在游戏现场

// MARK: Methods
func addBall(timer:NSTimer?){

    if (appDelegate.isGameOver) {
         return
    }

    //.....
    // all logic here...
}

通过这种方式,您只需使用标志来控制计时器,我在游戏中实现了这一点,并为我工作。

欢迎使用SO,我们不是来编写代码的。请添加一个详细的代码。解释为什么它对你不起作用,以及你期望它做什么。我回答了你的问题。我和你有同样的问题。若你们照我说的做,你们可以在游戏场景中使用定时器。如果我的答案对您有帮助,请点击绿色复选标记@好极了,我会试试的!根据我在谷歌上搜索到的答案,许多人建议使用NSNotificationcenter。我将尝试这两种方法,看看哪一种效果更好。这对我非常有用。