将SCNScene分配给SCNView - 在解包可选值时找到nil

时间:2018-01-26 01:23:42

标签: swift scenekit

最近,我决定运用我以前的C ++和Python知识来学习Swift。之后,我决定看看我能用SceneKit框架做些什么。经过几个小时的文档检查和咨询教程,我不得不想知道我的代码出了什么问题:

class GameViewController: UIViewController {
   var gameView:SCNView!
   var gameScene:SCNScene!
   var cameraNode:SCNNode!

   override func viewDidLoad() {
      super.viewDidLoad()

      initScene()
      initView()
      initCamera()
   }

   func initView() {        
      //initialize the game view - this view holds everything else in the game!
      gameView = self.view as! SCNView

      //allow the camera to move to gestures - mainly for testing purposes
      gameView.allowsCameraControl = true
      //use default lighting while still practicing
      gameView.autoenablesDefaultLighting = true
   }

   func initScene() {
      //initialize the scene
      gameScene = SCNScene()
      //set the scen in the gameView object to the scene created by this function
      gameView.scene = gameScene
   }

   func initCamera() {
      //create a node that will become the camera
      cameraNode = SCNNode()
      //since a node can be any object in the scene, this needs to be set up as a camera
      cameraNode.camera = SCNCamera()
      cameraNode.position = SCNVector3 (x:0, y:5, z:15)
   }
}

在对文档进行更多检查并确保我现在直接从教程中复制以使其工作之后,我仍然没有运气。根据我在StackOverflow上找到的很多其他问题,看起来它与强制解包,感叹号有关,但我不确定为什么会这样。

我可能一直在盯着这个文档,但我还没看到问题所在。

另外,如果我的评论有点长和/或分散注意力,请道歉。

1 个答案:

答案 0 :(得分:1)

您有以下问题:

1)您应该在viewDidLoad中重新排序初始化,这样做:

initView() // must be initialized before the scene 
initScene() // you have been crashing here on getting `gameView.scene`, but gameView was nil
initCamera()

2)cameraNode未附加在rootNode上,因此您可以在initCamera末尾添加以下代码:

gameScene.rootNode.addChildNode(cameraNode)