Search code examples
swiftswiftuiaugmented-realityrealitykit

Remove Entity from Scene in RealityKit


I want to remove an Entity from my Scene.

I created my Entity inside of the UpdateUIView function like this:

// create anchor and model-Entity
let anchor = AnchorEntity(plane: .horizontal)
    
let cube = MeshResource.generateBox(size: 0.1, cornerRadius: 0.03)
let material = SimpleMaterial(color: .gray, roughness: 0.2, isMetallic: true)
let cubeEntity = ModelEntity(mesh: cube, materials: [material])
    
anchor.addChild(cubeEntity)
uiView.scene.addAnchor(anchor)

Now I want to remove it, by pressing a Button in my User Interface. By pressing the button I change a var from false to true. Then I wrote inside the UpdateUIView function:

if remove == true {
    uiView.scene.removeAnchor(anchor)
}

When I press the button it changes the Boolean to true but the Entity does not disappear.

Any suggestions on how to solve this problem?


Solution

  • updateUIView(...)

    Use the following code to get a desired result:

    import SwiftUI
    import RealityKit
    
    struct ARViewContainer: UIViewRepresentable {
        
        @Binding var showed: Bool
        let anchor = AnchorEntity(world: [0, 0,-1])
        
        func makeUIView(context: Context) -> ARView {      
            let arView = ARView(frame: .zero)
            let cube = MeshResource.generateBox(size: 0.8, cornerRadius: 0.02)
            let material = SimpleMaterial(color: .red, isMetallic: true)
            let cubeEntity = ModelEntity(mesh: cube, materials: [material])
            anchor.addChild(cubeEntity)
            arView.scene.addAnchor(anchor)
            return arView
        }        
        func updateUIView(_ uiView: ARView, context: Context) {
            if showed == true {
                uiView.scene.removeAnchor(anchor)
            }
        }
    }
    

    struct ContentView : View {
        
        @State private var show = false
    
        var body: some View {
            VStack {
                ARViewContainer(showed: $show)
                VStack {
                    Button(action: { self.show.toggle() }) {
                        Text("Remove Model")
                    }
                }
            }
        }
    }    
    

    Coordinator

    It's not obligatory to update your content inside updateUIView(...) instance method. Instead you could use Coordinator class with custom makeCoordinator() method.