我正在 Swift 中开发一个 ARKit 项目,我试图接收 AR 锚点并在 AR 场景中每个检测到的锚点处放置一个小球体。我有一个符合 ARSessionDelegate 的 AppModel 类,它管理 AR 会话和场景内容。
我收到以下错误:
Call to main actor-isolated instance method ‘createSphereEntity(radius:)’ in a synchronous nonisolated context
如何解决?
import Foundation
import RealityAR
import SwiftUI
import ARKit
import RealityKit
@MainActor
@Observable
class AppModel: NSObject, ARSessionDelegate {
let session = ARSession()
// let sceneRecostruction = SceneReconstructionProvider()
// let handTracking = HandTrackingProvider()
var arView: ARView!
var objectInScene = Entity()
override init() {
super.init()
setupARView()
}
func setupARView() {
// Initialize the ARView
arView = ARView(frame: .zero)
arView.session.delegate = self // Set ARSessionDelegate
// Create AR session configuration
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = [.horizontal, .vertical]
// Enable scene reconstruction if needed
if ARWorldTrackingConfiguration.supportsSceneReconstruction(.mesh) {
configuration.sceneReconstruction = .mesh
}
// Run AR session
arView.session.run(configuration)
print("Session running")
}
func loadModel() async {
// Add the initial RealityKit content
if let person = try? await Entity(named: "person", in: realityARBundle) {
let radians = 180.0 * Float.pi / 180.0
person.transform.rotation = simd_quatf(angle: radians,axis: SIMD3<Float>(0,1,0))
person.scale = SIMD3(0.5, 0.5, 0.5)
person.components.set(GroundingShadowComponent(castsShadow: true))
let anchor = AnchorEntity(.plane(.horizontal, classification: .table, minimumBounds: SIMD2(0.5, 0.5)))
anchor.addChild(person)
arView.scene.addAnchor(anchor)
} else {
print("Couldn't load the character")
}
}
// Helper function to create a sphere entity
func createSphereEntity(radius: Float) -> ModelEntity {
let mesh = MeshResource.generateSphere(radius: radius)
let material = SimpleMaterial(color: .blue, isMetallic: false)
return ModelEntity(mesh: mesh, materials: [material])
}
nonisolated func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
let spere = createSphereEntity(radius: 0.1) // <------ error here
}
}
您的调用位于显式标记为
nonisolated
的函数内部,但该函数与主线程隔离,因此您必须异步调用它。
nonisolated func session(_ session: ARSession, didAdd anchors: [ARAnchor]) async {
let spere = await createSphereEntity(radius: 0.1)
}