RealityKit ModelComponent problems with SurfaceShader

I trying to use CustomMaterial with surfaceShader, followed this article

https://developer.apple.com/documentation/realitykit/modifying_realitykit_rendering_using_custom_materials

but my model not appear after I try obtain customMaterial to modelComponent, I catch error. How to use surfaceShader on usdz model? Have a good day!

private func obtainUSDZModel() {

        guard let doll = try? Entity.load(named: "Doll") else { return }

        

        guard var modelComponent = doll.components[ModelComponent.self] as? ModelComponent else { 
       print("Error Model Component")
       return
      }



        let surfaceShader = CustomMaterial.SurfaceShader(named: "rainbow",  in: MetalLibLoader.library)



        guard let customMaterials = try? modelComponent.materials.map({ material -> CustomMaterial in

            let customMaterial = try CustomMaterial(from: material, surfaceShader: surfaceShader)

            return customMaterial

        }) else { return }



        modelComponent.materials = customMaterials

        doll.generateCollisionShapes(recursive: true)

        doll.components[ModelComponent.self] = modelComponent

        doll.scale = .init(repeating: 1.0)

        anchorEntity.addChild(doll)

        arView.scene.anchors.append(anchorEntity)
    }

console output:

Error Model Component
Answered by Graphics and Games Engineer in 691171022

Try what is suggested above, you can also try using the loadModel API. But the rest of your code looks correct.

This seems to indicate that the "doll" Entity does not have a ModelComponent, at least not at the top level of its entity hierarchy.

I recommend that you print(doll) so that you can see what the structure of the entity hierarchy is like. You may find that the ModelComponent(s) are deeper in the hierarchy.

Accepted Answer

Try what is suggested above, you can also try using the loadModel API. But the rest of your code looks correct.

RealityKit ModelComponent problems with SurfaceShader
 
 
Q