簡體   English   中英

由於內存問題在后台線程上加載SpriteKit場景導致應用程序崩潰

[英]Loading SpriteKit scene on background thread causes app to crash because of memory issues

我有這個奇怪的問題。 在我的游戲中,我從.sks文件加載場景。 當我將其加載到主線程上時,我沒有任何問題。 一切都很好。 但是,當我在后台線程上加載時,由於內存問題,應用程序崩潰了。 這是我的代碼...

DispatchQueue.global(qos: .background).async {
    let nextScene = World(fileNamed: "GameScene")
        DispatchQueue.main.async {
            self.nextScene = nextScene
            self.playerRunningState = .RUNNINGRIGHT
        }
}

有誰知道為什么這會在主線程上起作用而不在后台線程上起作用。

僅供參考,它在以下行崩潰:

let nextScene = World(fileNamed: "GameScene")

如Apple文檔中所述,在操作節點時,SpriteKit不是線程安全的: https : //developer.apple.com/documentation/spritekit/sknode

對節點的操作必須在主線程中進行。 SKViewDelegate,SKSceneDelegate和SKScene的所有SpriteKit回調都發生在主線程中,這些是對節點進行操作的安全位置。 但是,如果您在后台執行其他工作,則應采用與清單1類似的方法。

所有操作都必須在主線程上同步發生,並且創建新節點是一種操作。 如果要對主線程之外的節點進行操作,則必須采用以下方法:

 class ViewController: UIViewController {
    let queue = DispatchQueue.global()

    var makeNodeModifications = false

    func backgroundComputation() {
        queue.async {
            // Perform background calculations but do not modify 
            // SpriteKit objects

            // Set a flag for later modification within the 
            // SKScene or SKSceneDelegate callback of your choosing

            self.makeNodeModifications = true
        }
    }
}
extension ViewController: SKSceneDelegate {
    func update(_ currentTime: TimeInterval, for scene: SKScene) {
        if makeNodeModifications {
            makeNodeModifications = false

            // Make node modifications
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM