gpt4 book ai didi

swift - SceneKit切换场景内存泄漏

转载 作者:行者123 更新时间:2023-11-30 10:51:47 28 4
gpt4 key购买 nike

我有两个空白场景对象,没有任何节点和摄像机:

func setupScenes() {
scnView = SCNView(frame: self.view.frame)
self.view.addSubview(scnView)

gameScene = SCNScene(named: "/MrPig.scnassets/GameScene.scn")
splashScene = SCNScene(named: "/MrPig.scnassets/SplashScene.scn")
scnView.scene = splashScene
}

显示每个场景的两种方法:

func startSplash() {
gameScene.isPaused = true
let transition = SKTransition.doorsOpenVertical(withDuration: 1.0)
scnView.present(splashScene, with: transition, incomingPointOfView: nil, completionHandler: {
self.gameState = .tapToPlay
self.setupSounds()
self.splashScene.isPaused = false
})
}

func startGame() {
splashScene.isPaused = true
let transition = SKTransition.doorsOpenVertical(withDuration: 1.0)
scnView.present(gameScene, with: transition, incomingPointOfView: nil, completionHandler: {
self.gameState = .playing
self.setupSounds()
self.gameScene.isPaused = false
})
}

以及用于在场景之间切换的触摸手势:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if gameState == .tapToPlay {
startGame()
} else {
startSplash()
}
}

每次我触摸屏幕时,屏幕上都会出现第一个或第二个场景,我已经习惯了加上 ~80Mb 的 RAM。10 次接触后,已使用 500MB RAM。

我不明白为什么会发生这种情况?

最佳答案

代码中明显的问题是,每次调用 startGame() 和 startSplash() 方法时,带有闭包的嵌套函数都会捕获具有强引用的“ self ”。

Some info about strong and weak references and ARC.

首先,您应该执行以下操作:

func startSplash() {
gameScene.isPaused = true
let transition = SKTransition.doorsOpenVertical(withDuration: 1.0)
scnView.present(splashScene, with: transition, incomingPointOfView: nil, completionHandler: { [weak self] in
guard let self = self else { return }
self.gameState = .tapToPlay
self.setupSounds()
self.splashScene.isPaused = false
})
}

func startGame() {
splashScene.isPaused = true
let transition = SKTransition.doorsOpenVertical(withDuration: 1.0)
scnView.present(gameScene, with: transition, incomingPointOfView: nil, completionHandler: { [weak self] in
guard let self = self else { return }
self.gameState = .playing
self.setupSounds()
self.gameScene.isPaused = false
})
}

其次,尽量不要使用touchesBegan方法,它可能会导致一些副作用。

希望对你有帮助!

关于swift - SceneKit切换场景内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54386840/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com