我正在尝试让动画在Swift中工作,但出现错误消息:


  致命错误索引超出范围


这是我正在使用的代码:

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

    }
}

最佳答案

呼叫TextureAtlas.textureNamesPlayer = SKSpriteNode(imageNamed: TextureAtlas.textureNames[0] as! String)为空。当您尝试从空数组中提取某些内容时发生崩溃。如果这是永远不应该为空的内容,那么您需要弄清楚为什么它为空并进行修复。否则,您可以默认为行内空白字符串:

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

09-27 12:39