如何正确初始化类

时间:2017-12-01 14:30:51

标签: ios swift class sprite-kit initialization

每当我尝试调用它时,以下代码都会在我的GameScene类的行pickUp.spawnShield()上产生错误。

编译器没有关于导致错误的原因的消息,但我认为这可能与我的var pickUp: Pickup!为零的事实有关。如果是这种情况,我该如何正确地初始化它?

class Pickup {

    var game: GameScene!

    func spawnShield() {

        let randomXStart = Random().random(min: game.gameArea.minX + game.player.size.width/2, max: game.gameArea.maxX - game.player.size.width/2)

        let randomXEnd = Random().random(min: game.gameArea.minX + game.player.size.width/2, max: game.gameArea.maxX - game.player.size.width/2)

        let startPoint = CGPoint(x: randomXStart, y: game.size.height * 1.1)
        let endPoint = CGPoint(x: randomXEnd, y: -game.size.height * 0.1)

        let shield = SKSpriteNode(imageNamed: "shieldDrop")
        shield.setScale(2)
        shield.position = startPoint
        shield.zPosition = 3

        game.addChild(shield)

        let moveShield = SKAction.move(to: endPoint, duration: TimeInterval(Helper().randomBetweenTwoNumbers(firstNumber: 3, secondNumber: 5)))

        shield.run(moveShield)
    }
}

然后我在课堂上这样称呼它:

class GameScene: SKScene, SKPhysicsContactDelegate {

    var pickUp: Pickup!

    override init(size: CGSize) {

        ....

        pickUp = Pickup() //something like this?

        super.init(size: size)
    }

    func startNewLevel() {

        pickUp.spawnShield()
    }
}

2 个答案:

答案 0 :(得分:2)

首先:你必须在var pickUp中创建一个存储(引用)的Pickup类实例。我没有看到像

这样的东西
class Pickup {
  weak var game: GameScene?
  init(game: GameScene) {
    self.game = game
  }
  func spawnShield() {...}
}

class GameScene: SKScene, SKPhysicsContactDelegate {
  var pickUp: Pickup!
  override init(size: CGSize) {
    super.init(size: size)
    pickUp = Pickup(game: self)
}

第二:我没有太多理由让pickUp隐式解包(!)。我宁愿提出弱var pickUp:Pickup?以避免引用周期(如果在周期中引用)

第三:奇怪的是你没有看到缺少初始化程序的编译错误,因为你的类中有属性,然后必须定义初始化程序。初始化类属性后,不要忘记在初始化程序中调用 super.init(...)

答案 1 :(得分:0)

在这里,我想你可以做这样的事情

class GameScene: SKScene, SKPhysicsContactDelegate {

    var pickUp = Pikup()

    func startNewLevel() {

        pickUp.spawnShield()
    }
}

或者你可以在调用spawnShield()之前初始化变量“pikUp”,也许在你编写的init方法中。

所以也要确保在初始化之后使用'game'变量,因为正如我在你的代码中看到的那样,它也会崩溃,因为当你使用它时它是零。