How to create objects based on a list?

So I am trying to create a certain amount of spheres in a SceneKit scene based on the number of objects in a list. So I think I would put an addChild in a for loop, but how would I assign them all to the same type of model? Especially because sometimes the list will be empty, so the model would not need to show up at all.

Answered by Riptide314 in 794911022

Figured it out, this works:

for sensor in self.sensors{
            node = SCNNode(geometry: SCNSphere(radius: 0.04))
            node.geometry?.firstMaterial?.diffuse.contents = UIColor.black
            node.castsShadow = true
            node.simdPosition = sensor.getLocation()
            node.name = "Sensor: \(sensor.getTag())"
            scene?.rootNode.addChildNode(node)
        }

Sensor is a data class that I wrote, it could be replaced with any other method of assigning a name or position.

Accepted Answer

Figured it out, this works:

for sensor in self.sensors{
            node = SCNNode(geometry: SCNSphere(radius: 0.04))
            node.geometry?.firstMaterial?.diffuse.contents = UIColor.black
            node.castsShadow = true
            node.simdPosition = sensor.getLocation()
            node.name = "Sensor: \(sensor.getTag())"
            scene?.rootNode.addChildNode(node)
        }

Sensor is a data class that I wrote, it could be replaced with any other method of assigning a name or position.

It is more efficient if you reuse the same geometry instance across all SCNNode instances, so create it outside the loop, then you will only get one draw call for all the spheres instead of one draw call per node.

Here is the updated answer:

var node: SCNNode
let geometry = SCNSphere(radius: 0.04)
geometry.firstMaterial?.diffuse.contents = UIColor.black
for device in self.devices{
            node = SCNNode(geometry: geometry)
            node.castsShadow = true
            node.simdPosition = device.getLocation()
            node.name = "Device: \(device.getTag())"
            scene?.rootNode.addChildNode(node)
        }
How to create objects based on a list?
 
 
Q