After adding gestures to the EntityModel, when it is necessary to remove the EntityModel, if the method uiView.gestureRecognizers?.removeAll() is not executed, the instance in memory cannot be cleared. However, executing this method affects gestures for other EntityModels in the ARView. Does anyone have a better method to achieve this?
Example Code:
struct ContentView : View {
@State private var isRemoveEntityModel = false
var body: some View {
ZStack(alignment: .bottom) {
ARViewContainer(isRemoveEntityModel: $isRemoveEntityModel).edgesIgnoringSafeArea(.all)
Button {
isRemoveEntityModel = true
} label: {
Image(systemName: "trash")
.font(.system(size: 35))
.foregroundStyle(.orange)
}
}
}
}
ARViewContainer:
struct ARViewContainer: UIViewRepresentable {
@Binding var isRemoveEntityModel: Bool
let arView = ARView(frame: .zero)
func makeUIView(context: Context) -> ARView {
let model = CustomEntityModel()
model.transform.translation.y = 0.05
model.generateCollisionShapes(recursive: true)
__**arView.installGestures(.all, for: model)**__ // here--> After executing this line of code, it allows the deletion of a custom EntityModel in ARView.scene, but the deinit {} method of the custom EntityModel is not executed.
arView.installGestures(.all, for: model)
let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(0.2, 0.2)))
anchor.children.append(model)
arView.scene.anchors.append(anchor)
return arView
}
func updateUIView(_ uiView: ARView, context: Context) {
if isRemoveEntityModel {
let customEntityModel = uiView.scene.findEntity(named: "Box_EntityModel")
// --->After executing this line of code, ARView.scene can correctly delete the CustomEntityModel, and the deinit {} method of CustomEntityModel can also be executed properly. However, other CustomEntityModels in ARView.scene lose their Gestures as well.
__** uiView.gestureRecognizers?.removeAll()**__
customEntityModel?.removeFromParent()
}
}
}
CustomEntityModel:
class CustomEntityModel: Entity, HasModel, HasAnchoring, HasCollision {
required init() {
super.init()
let mesh = MeshResource.generateBox(size: 0.1)
let material = SimpleMaterial(color: .gray, isMetallic: true)
self.model = ModelComponent(mesh: mesh, materials: [material])
self.name = "Box_EntityModel"
}
deinit {
**print("CustomEntityModel_remove")**
}
}