<分区>
我正在尝试将音乐添加到我创建的游戏中。但我收到错误:
"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.
我在 Stack Overflow (What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?) 上找到了另一篇文章,但我不明白这如何适用于我的代码。
这是我的代码:
import UIKit
import SpriteKit
import GameplayKit
import AVFoundation
class GameViewController: UIViewController {
var player:AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
do {
let audioPath = Bundle.main.path(forResource: "HomeSoundtrack", ofType: "m4a")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
}
catch {
}
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayback)
}
catch {
}
player.play()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = false
view.showsNodeCount = false
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
}