【问题标题】:Assigning SCNScene to SCNView - found nil while unwrapping Optional value将 SCNScene 分配给 SCNView - 在展开可选值时发现 nil
【发布时间】:2018-01-26 09:59:55
【问题描述】:

最近,我决定将以前在 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 上找到的许多其他问题,它看起来与强制展开、感叹号有关,但我不确定这是为什么。

我可能一直在通过本文档梳理答案,但我不太明白问题出在哪里。

另外,如果我的 cmets 有点长和/或分散注意力,我们深表歉意。

【问题讨论】:

    标签: swift scenekit


    【解决方案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)
    

    【讨论】:

    • 谢谢!我从来没有注意到我的顺序错误!我想我是从错误的方向看这个的。
    猜你喜欢
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    相关资源
    最近更新 更多