iOS SwiftUI+RealityKit:实现清除AR场景所有3D物体的按钮
清除AR场景中全部3D物体的实现方案
核心思路
RealityKit的场景内容依托Entity层级管理,要清除所有导入的3D物体,核心是遍历并移除场景中所有自定义添加的实体(需保留AR系统自带的锚点实体,避免破坏AR追踪)。
具体实现步骤
1. 在CustomARView中添加清除方法
在你的CustomARView类里新增清除逻辑:
extension CustomARView { func clearAll3DObjects() { // 遍历所有锚点下的子实体,移除自定义导入的模型 scene.anchors.forEach { anchor in // 若你的模型有统一命名标识,可通过名称过滤;无标识则直接移除所有子实体 let targetEntities = anchor.children.filter { $0.name?.contains("ImportedModel") ?? false } targetEntities.forEach { $0.removeFromParent() } } // 若模型直接添加到场景根节点,用以下逻辑 // let rootEntities = scene.children.filter { $0.name?.contains("ImportedModel") ?? false } // rootEntities.forEach { $0.removeFromParent() } } }
注:建议给每个导入的3D实体设置统一名称(比如entity.name = "ImportedModel"),这样能精准过滤,避免误删AR系统锚点。
2. 在ContentView中添加清除按钮
在SwiftUI视图里添加交互按钮,调用上述清除方法:
struct ContentView: View { @State private var arView = CustomARView(frame: .zero) var body: some View { ZStack { ARViewContainer(arView: $arView) .edgesIgnoringSafeArea(.all) VStack { Spacer() Button(action: { arView.clearAll3DObjects() }) { Text("清除所有物体") .padding() .background(Color.red) .foregroundColor(.white) .cornerRadius(10) } .padding(.bottom, 30) } } } } // ARView的SwiftUI包装容器 struct ARViewContainer: UIViewRepresentable { @Binding var arView: CustomARView func makeUIView(context: Context) -> CustomARView { arView } func updateUIView(_ uiView: CustomARView, context: Context) {} }
3. 特殊场景适配
- 若模型是添加到自定义
AnchorEntity上,可直接移除对应锚点提升效率:
func clearAll3DObjects() { scene.anchors.removeAll(where: { !($0 is ARAnchorEntity) }) }
- 若需保留平面检测锚点,仅移除模型实体,严格通过名称或标签过滤即可。
内容的提问来源于stack exchange,提问作者Tavi
相关产品推荐
相关产品推荐

