3

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.

Bryan
  • 43
  • 1
  • 5

1 Answers1

7

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.

Alan
  • 1,132
  • 7
  • 15
  • Thank you so much - this worked. For others trying to use this method with ARKit, I'd recommend making the SCNNode programmatically like this, then just adding it as a virtualObject via the code too. It's easier to debug and works. – Bryan Oct 27 '17 at 02:09
  • Please just don't forgot to mark the answer if it worked for you. Glad I managed to help :) – Alan Oct 27 '17 at 07:42
  • How can I just add the material to one side? – helloworld12345 Jul 16 '21 at 01:25