Spritekit Swift 终止错误

Spritekit Swift Terminating Error

我正在尝试在 sprite kit 中制作一个具有随机彩色背景的新应用程序,我所做的只是设置背景颜色并在游戏中创建一个球,但它不会首先启动我'我会给出我的代码,然后给出错误。到目前为止,这是我的代码。

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate{

struct PhysicsCategory {
static let None      :UInt32 = 0
static let All       :UInt32 = UInt32.max
static let Triangle  :UInt32 = 0b1   //body1
static let Circle    : UInt32 = 0b10      // 2
 }

var screenWidth: CGFloat! = 0

var screenHeight: CGFloat! = 0


var circle: SKShapeNode! = SKShapeNode()
var bgColor:SKColor!
var arrayOfColors: NSMutableArray! = NSMutableArray()
var backgroundNode: SKSpriteNode! = SKSpriteNode()

override func didMoveToView(view: SKView) {
    super.didMoveToView(view)
    // Create the ball
    if screenWidth == 1024{
        circle = SKShapeNode(circleOfRadius: 22)
    }else if screenWidth == 568 || screenWidth == 480{
        circle = SKShapeNode(circleOfRadius: 11)
    }else{
        circle = SKShapeNode(circleOfRadius: 15)
    }

    circle.fillColor = SKColor.whiteColor()
    circle.alpha = 0
    circle.physicsBody = SKPhysicsBody(circleOfRadius: circle.frame.size.width/2)
    circle.physicsBody?.dynamic = true
    circle.physicsBody?.collisionBitMask = PhysicsCategory.None
    circle.physicsBody?.usesPreciseCollisionDetection = true
    circle.position = CGPoint (x: 29.952, y: 346.555)

    self.addChild(circle)

    //pick random color
    let UInt32Count = UInt32(arrayOfColors.count)
    let randomColor = arc4random_uniform(UInt32Count)
    let color: SKColor = arrayOfColors[Int(randomColor)] as SKColor

    //set random color
    let colorAction = SKAction.colorizeWithColor(color, colorBlendFactor: 1.0, duration: 1.0)
    backgroundNode.runAction(colorAction)
    backgroundNode.size = CGSize(width: 990, height: 640)

    }


 }

这是到目前为止的完整代码,这里是错误。

由于未捕获的异常 'NSRangeException',正在终止应用程序,原因:“* -[__NSArrayM objectAtIndex:]:索引 0 超出空数组的范围” * 首先抛出调用栈: (0x24c8d5f7 0x324ffc77 0x24ba1157 0x341ec 0x346d8 0x27fb9861 0x27fd4023 0x37888 0x379b0 0x28131c8d 0x281319fd 0x281378c7 0x2813531f 0x2819f5c1 0x283915f1 0x28393a49 0x2839e2f9 0x283922eb 0x2b4030c9 0x24c53ffd 0x24c532c1 0x24c51e1b 0x24b9eb31 0x24b9e943 0x28196127 0x28190f21 0x3a2e8 0x3a324 0x32a9baaf) libc++abi.dylib:以 NSException 类型的未捕获异常终止 (lldb)

如有任何帮助,我们将不胜感激

您已经声明并初始化了您的空数组:

var arrayOfColors: NSMutableArray! = NSMutableArray()

然后您正在尝试访问空数组:

let color: SKColor = arrayOfColors[Int(randomColor)] as SKColor

这将引发异常,如您在控制台中所示:

'* -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'

您首先需要在访问之前填充此数组,并确保生成随机数时不超出数组范围。