swiftswiftuiscenekitusdz

SceneKit – Changing colors of USDZ model


I created a view with SceneKit using a USDZ file, how can I change the colors of a particular material from gray to something else directly in the SwiftUI code?

enter image description here

var scene = SCNScene(named: "2020_BMW_M5.usdz")
var body: some View {       
    VStack {
        SceneView(scene: scene, 
                options: [.autoenablesDefaultLighting, .allowsCameraControl])
    }
}

Solution

  • Use a subscript approach (.childNodes[n].childNodes[n].childNodes[n]) to get to model in desired hierarchy, and then change its color as usually:

    import SwiftUI
    import SceneKit
    
    struct ContentView : View {
        var body: some View {
            return SceneKitViewContainer().ignoresSafeArea()
        }
    }
    
    struct SceneKitViewContainer: UIViewRepresentable {
        
        func makeUIView(context: Context) -> SCNView {
            let scnView = SCNView(frame: .zero)
            scnView.allowsCameraControl = true
            scnView.autoenablesDefaultLighting = true
            scnView.scene = SCNScene(named: "Model.usdz")
            
            let model = scnView.scene?.rootNode.childNode(withName: "SomeModel", 
                                                       recursively: true)
            model?.childNodes[1].geometry?.firstMaterial?.diffuse.contents = 
                                                                    UIColor.red
            print(model?.childNodes[1])
    
            return scnView
        }
        func updateUIView(_ uiView: SCNView, context: Context) { }
    }