Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import an obj file in Scenekit macOS App

I am trying to read a .obj file into a SCNNode from the local drive on a macOS app (not iOS) with the following code:

let url = NSURL(string: objPath!)
let asset = MDLAsset(url: url! as URL)
       
let node = SCNNode(mdlObject: asset.object(at: 0))
node.geometry?.firstMaterial?.diffuse.contents = NSColor.red
        
scnView.scene?.rootNode.addChildNode(node)

The objPath is correct and absolute path to a local folder (not inside app build). But it's giving "Could not open OBJ file" error while reading. I need to access local path only.

like image 493
Sarbartha Sengupta Avatar asked Oct 23 '25 05:10

Sarbartha Sengupta


1 Answers

This should let you load an obj/dae file in swift/xcode 10.2+:

Create a scenekit model catalog by going to File --> New --> File and selecting "SceneKit Catalog" from the list.

import SceneKit.ModelIO

Then:

guard let url = Bundle.main.url(forResource: "your_obj_filename", withExtension: "obj", subdirectory: "your_folder.scnassets") 
     else { fatalError("Failed to find model file.") }

let asset = MDLAsset(url:url)
guard let object = asset.object(at: 0) as? MDLMesh 
     else { fatalError("Failed to get mesh from asset.") }

let newNode  = SCNNode(mdlObject: object)
like image 65
Jubei Avatar answered Oct 24 '25 18:10

Jubei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!