1

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) {

    }
}
4
  • Which line gives you the index of out bounds error? Commented Jul 18, 2016 at 20:27
  • Player = SKSpriteNode(imageNamed: TextureAtlas.textureNames[0] as! String) seems to be the problem Commented Jul 18, 2016 at 20:28
  • 3
    Shot in the dark, but are your atlas images named starting with 0 or 1? Referring to this line: i in 1...TextureAtlas.textureNames.count, which would be i in 0..<TextureAtlas.textureNames.count if starting with 0. Commented Jul 18, 2016 at 20:30
  • Always check if the index exists if you aren't 100% certain it does and then consider adding a mechanism that converts out-of-bounds indices into in-bounds indices. For instance, if the index doesn't exist because the integer is too high, use the last index in the array, and if the index doesn't exist because the integer is too low, use 0. Commented Dec 24, 2019 at 16:15

1 Answer 1

1

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 ?? "")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.