【发布时间】:2016-01-20 01:58:52
【问题描述】:
我正在创建我的第一个游戏,从 GameOverScene 回来后它崩溃了。这是给我错误的部分:
// GameScene.swift
// Test_Crash_1
import SpriteKit
struct global {
static var wheelRotPlat2 = SKShapeNode(circleOfRadius: 400)
static var button : SKShapeNode = SKShapeNode()
static var actualPlayer : String = String()
static let btnNextPlayer = SKShapeNode(circleOfRadius: 70)
}
class GameScene: SKScene {
deinit {
print("The GameScene has been removed from memory")
}
override func didMoveToView(view: SKView) {
let buttonDice = SKShapeNode(rectOfSize: (CGSizeMake(40,40)), cornerRadius: 5)
global.button = buttonDice
global.button.position = CGPoint(x: (CGRectGetMidX(self.frame)-400), y:(CGRectGetMidY(self.frame)-350))
global.button.fillColor = UIColor(red: 0.2, green: 1.0, blue: 0.2, alpha: 0.8)
global.button.name = "button"
global.button.zPosition = 1
addChild(global.button)
global.wheelRotPlat2.addChild(global.btnNextPlayer)
global.btnNextPlayer.name = "btnNextPlayer"
} // end didMoveToView
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches //as! Set<UITouch>
let location = touch.first!.locationInNode(self)
let node = self.nodeAtPoint(location)
if (node.name == "button") {
self.removeAllActions()
self.removeAllChildren()
let reveal = SKTransition.flipHorizontalWithDuration(0.5)
let gameOverScene = GameOverScene(size: self.size, player: global.actualPlayer)
self.view?.presentScene(gameOverScene, transition: reveal)
}
} // End func touchesBegan
} // end GameScene
还有 GameOverScene 文件:
// GameOverScene.swift
// Test_Crash_1
import Foundation
import SpriteKit
class GameOverScene: SKScene {
init(size: CGSize, player: String) {
super.init(size: size)
backgroundColor = SKColor.whiteColor()
runAction(SKAction.sequence([
SKAction.waitForDuration(3.0),
SKAction.runBlock() {
let reveal = SKTransition.flipHorizontalWithDuration(0.5)
let scene = GameScene(size: size)
self.view?.presentScene(scene, transition:reveal)
}
]))
} // end init(size
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} // end GameOverScene
这个错误是众所周知的:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attemped to add a SKNode which already has a parent: SKShapeNode name:'btnNextPlayer'
此示例只有一个绿色按钮,可将我带到 GameOverScene。当它返回时游戏崩溃。
我不明白为什么会发生这种情况。 谁能告诉我为什么会发生这种情况以及如何解决?
【问题讨论】:
-
除了 KnightOfDragon 的回答和我对他的问题的评论之外,您在 GameOverScene 中有一个保留周期。您不能像在闭包中那样使用 self 。你应该使用弱或无主的自我。搜索关于那个...
标签: ios swift crash sprite-kit