Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically assign a material to a 3D SCNNode?

I'm trying to figure out how to programmatically assign a material to some object (SCNNode) in my scene for ARKit (XCode 9 / Swift 4). I'm trying to programmatically do this because I want the same shaped object to be rendered with way too many variants (or user-generated images) to be able to do it via the menu assignment in a scene. The object just a cube - for now, I'm just trying to get one side to display this material pulled from the Assets folder.

This is the current code that I've tried referencing prior Stack posts, but the object is just remaining white.

let material = SCNMaterial()
material.diffuse.contents = UIImage(named: "texture.jpg")

let nodeObject = self.lastUsedObject?.childNode(withName: "box", recursively: true)
// I believed this lets me grab the last thing I rendered in an ARKit scene - please
// correct me if I'm wrong.  My object is also labeled "box".
nodeObject?.geometry?.materials
nodeObject?.geometry?.materials[0] = material // I wanted to grab the first face of the box

Thank you so much in advance! I've been fiddling with this for a while but I can't seem to get the grasp of programmatic methods for 3D objects / Scenes in Swift.

like image 1000
Bryan Avatar asked Jan 31 '26 05:01

Bryan


1 Answers

Overall, I was setting the materials of an object like this and it was working (to only grab one face of the box

var imageMaterial = SCNMaterial()
imageMaterial.isDoubleSided = false
imageMaterial.diffuse.contents = UIImage(named: "myImage")
var cube: SCNGeometry? = SCNBox(width: 1.0, height: 1.0, length: 1, chamferRadius: 0)
var node = SCNNode(geometry: cube)
node.geometry?.materials = [imageMaterial]

So it could possibly be that you haven't been able to grab the object, as stated in the comments.

like image 186
Alan Avatar answered Feb 02 '26 23:02

Alan



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!