Reality Kit on Swift Playgrounds

Hi Developers,

How do I pass a Reality Kit file to use the Reality Kit file for the AR experience:

import SwiftUI import RealityKit

struct HelpAR : View { var body: some View { ARViewContainer().edgesIgnoringSafeArea(.all) } }

struct ARViewContainer: UIViewRepresentable {

func makeUIView(context: Context) -> ARView {
    
    let arView = ARView(frame: .zero)
    
    // Create a cube model
    let mesh = MeshResource.generateBox(size: 0.1, cornerRadius: 0.005)
    let material = SimpleMaterial(color: .gray, roughness: 0.15, isMetallic: true)
    let model = ModelEntity(mesh: mesh, materials: [material])
    model.transform.translation.y = 0.05
    
    // Create horizontal plane anchor for the content
    let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(0.2, 0.2)))
    anchor.children.append(model)
    
    // Add the horizontal plane anchor to the scene
    arView.scene.anchors.append(anchor)
    
    return arView
    
}

func updateUIView(_ uiView: ARView, context: Context) {}

}

#Preview { HelpAR() }

Replies

Use the code below. (If the Reality Kit File is large, I recommend using the loadModelAsync function.)

If your Reality Kit file is a usdz file, try using loadModel instead of loadAnchor.

Hope this helps.

    func makeUIView(context: Context) -> ARView {
        
        let arView = ARView(frame: .zero)
        
        // Create a cube model
        let model = try? Entity.loadAnchor(named: "RealityKitFilename")
        
        // Create horizontal plane anchor for the content
        let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(0.2, 0.2)))
        if let model = model {
            anchor.children.append(model)
            
            // Add the horizontal plane anchor to the scene
            arView.scene.anchors.append(anchor)
        }
        return arView
        
    }

Thanks for your help :),

I got a question about Reality Composer Project. How do I compress a Reality Composer Project as mine is showing up to 125MB. The file size limit is 25 MB for the Swift Student Challenge

Thanks