SceneKit - Replace material to an array of nodes

Viewed 53

Goal: add default material to all child node on a Scenekit scene.

What I did:

// get child noses from scene
let allNodes = scene.rootNode.childNodes

//create a defaul material
let defaultMaterial = SCNMaterial()  
defaultMaterial.diffuse.contents = NSColor.red
         
//add defaul material to all child nodes
allChildNodes.replaceMaterial(at: 0, with: defaultMaterial)

Problem:

Looks like "replaceMaterial" doesn't work with an array of nodes.

Question:

How I add a material to an array of nodes?

1 Answers

Try this code:

import SceneKit

class GameViewController: NSViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let sceneView = self.view as! SCNView
        let scene = SCNScene(named: "art.scnassets/scene.scn")!
        sceneView.scene = scene
        
        let material = SCNMaterial()
        material.diffuse.contents = NSColor.systemYellow
        
        let allNodes = scene.rootNode.childNodes[0].childNodes
                
        for i in 0...(allNodes.count-1) {
            allNodes[i].geometry?.firstMaterial = material
        }
    }
}

enter image description here

enter image description here

Related