-1

I want to make a game when a player touches screen, a gem is showing up on the screen, but I have an error Fatal error: Unexpectedly found nil while unwrapping an Optional value. How to fix it?

I doing this:

var gem : SKSpriteNode!

override func touchesBegan(_ touches: Set<UITouch>, with the event: UIEvent?) {

    gem = SKSpriteNode(fileNamed: "CoolGem")!
    gem.position = CGPoint(x: 0, y: 0)
    addChild(gem)
    gem.run(SKAction.move(to: CGPoint(x: Double.random(in: -100...100), y: Double.random(in: -100...100)), duration: 1))

}

The error tells me this: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value on the 3rd line

Saveen
  • 4,120
  • 14
  • 38
  • 41
ExeRhythm
  • 452
  • 5
  • 13

2 Answers2

0

From the looks of it, there's no file named CoolGem. Since you used force unwrapping (!), the app crashes because your gem variable is nil.

Adis
  • 4,512
  • 2
  • 33
  • 40
0

is the image added to your project? is it in an asset catalog?

if so try accessing it like so

gem = SKSpriteNode(imageNamed: "Gem")

or you can ensure that it won't be nil

if let gem = SKSpriteNode(imageNamed: "Gem") as? SKSpriteNode {
    self.gem = gem
    gem.position = CGPoint(x: 0, y: 0)
    addChild(gem)
    gem.run(SKAction.move(to: CGPoint(x: Double.random(in: -100...100), y: Double.random(in: -100...100)), duration: 1))
}
Ron Myschuk
  • 6,011
  • 2
  • 20
  • 32