William Putnam William Putnam - 4 years ago 180
Swift Question

Can't use multiple images for SCNPlane array

I have an array of SCNPlane objects, and I want to add different images to each one. My problem is that whenever I initialize the SCNPlanes in the for loop, each plane will end up with the exact same image. Here is what my loop basically looks like:

var layer = [CALayer](count: 8, repeatedValue: CALayer())
var tmpPhoto = [CGImage]()

for var i = 0; i < 8; ++i{
tmpPhoto.append("image data")
layer[i].contents = tmpPhoto[i]
layer[i].frame = CGRectMake(0, 0, "image width", "image height")

//initialize the SCNPlane and add it to an array of SCNNodes

plane[i].geometry?.firstMaterial?.locksAmbientWithDiffuse = true
plane[i].geometry?.firstMaterial?.diffuse.contents = layer[i]

//add SCNPlane constraints
}


What I've noticed is that the image displayed will be the last image that was added/altered. I know this because after this loop, I tried modifying the first entry in the plane array only. At run time, the image for the first array entry would be displayed on all the other SCNPlanes instead! Keep in mind that I am not using displayLayer() or setNeedsDisplay() at all.

Here is what I have tried:


  • using a similar layer variable instead of an array, and just modifying it at the start of each loop

  • manipulating layer variables outside of a loop

  • directly adding on a UIImage without converting to CGImage first (I know that each image is being loaded into the array)

  • trying to modify the SCNPlane's layer directly

  • using an SCNMaterial variable (followed this, but with one layer added to the materials variable for each SCNPlane)

  • adding the layers to existing view structures using either addSublayer() (doesn't work) or layoutSublayersOfLayer() (crashes the app due to an uncaught exception)



Could I be missing something important?

EDIT: Forgot a line.

Answer Source

Create a different SCNPlane for each SCNNode. If you create a single SCNPlane for multiple nodes then they will share the geometry. Setting a material on the geometry will change all nodes that use that geometry.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download