void00
void00

Reputation: 29

Swift array: fatal error index out of range

I am trying to get an animation to work in Swift but I get an error that says:

fatal error Index out of range

Here is the code I am using:

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    var Player = SKSpriteNode()
    var TextureAtlas = SKTextureAtlas()
    var TextureArray = [SKTexture]()

    override func didMove( to view: SKView) {

        TextureAtlas = SKTextureAtlas(named: "images")

        for i in 1...TextureAtlas.textureNames.count{

            var Name = "front_\(i).png"
            TextureArray.append(SKTexture(imageNamed: Name))
        }

        Player = SKSpriteNode(imageNamed: TextureAtlas.textureNames[0] as! String)

        Player.size = CGSize(width: 100, height: 150)
        Player.position = CGPoint(x: self.size.width, y: self.size.height)
        self.addChild(Player)

        backgroundColor = (UIColor.cyan())
    }

    func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        Player.run(SKAction.repeatForever(SKAction.animate(with: TextureArray, timePerFrame: 1.5)))
    }

    override func update(_ currentTime: CFTimeInterval) {

    }
}

Upvotes: 1

Views: 3835

Answers (1)

keithbhunter
keithbhunter

Reputation: 12334

TextureAtlas.textureNames is empty when you call Player = SKSpriteNode(imageNamed: TextureAtlas.textureNames[0] as! String). The crash happens when you try to pull something out of an empty array. If this is something that should never be empty, then you need to figure out why it is empty and fix it. Otherwise, you can default to a blank string in-line:

Player = SKSpriteNode(imageNamed: TextureAtlas.textureNames[0] as? String ?? "")

Upvotes: 1

Related Questions