Search code examples
swiftaugmented-realityarkitrealitykit

Apply a custom texture to Plane entity using RealityKit 2.0


I i want to apply a custom text like a "grid" to a Plane Entity in RealityKit but I can't find the updated solution. so far I have try this code:

func createBoard() {
    let planeMesh = MeshResource.generatePlane(width: 1, 
                                              height: 1, 
                                        cornerRadius: 0.2)
    var myMaterial = SimpleMaterial()
    myMaterial.baseColor = try! .texture(.load(named: "texture.png")) 

    //'baseColor' was deprecated in iOS 15.0: use `color` property instead
    myMaterial.metallic = MaterialScalarParameter(floatLiteral: 0.5)
    myMaterial.roughness = MaterialScalarParameter(floatLiteral: 0.5)
    myMaterial.tintColor = UIColor.blue

    //'tintColor' was deprecated in iOS 15.0: use `color` property instead
    let modelEntity = ModelEntity(mesh: planeMesh, materials: [myMaterial])
}

But I'm getting the warning that base color and tintcolor are deprecated on iOS 15, I can't find the way to correct this issue.

Thanks for the help.


Solution

  • You have to implement brand-new parameters instead of deprecated arguments:

    func createBoard() {
        
        let planeMesh = MeshResource.generatePlane(width: 1,
                                                  height: 1,
                                            cornerRadius: 0.05)
        
        var material = SimpleMaterial()
        
        material.color = try! .init(tint: .white,
                                 texture: .init(.load(named: "img", in: nil)))
        material.metallic = .init(floatLiteral: 1.0)
        material.roughness = .init(floatLiteral: 0.5)
    
        let modelEntity = ModelEntity(mesh: planeMesh,
                                 materials: [material])
        
        let anchor = AnchorEntity()
        anchor.addChild(modelEntity)
        arView.scene.anchors.append(anchor)
    }
    

    Also, you can use the following syntax:

    var material = SimpleMaterial()
    material.color.texture = .init(try! .load(named: "img", in: nil))
    

    If you need mode details, read this post.