swiftmacosrealitykitskybox

Unable to load a RealityKit .skybox image from Xcode folder reference


I am creating a simple macOS app in SwiftUI to view RealityKit entities with .skybox lighting applied. Specifically, I found this and this, which I used for guidance.

I have created a "Lighting.skybox" folder on my Desktop with one .exr (from AmbientCG) file inside, and added the folder as a reference to the project. The folder icon in Xcode has the arrow to prove this. In Xcode, when I click on the .exr file, it is correctly displayed in the main window.

My problem however is that the app crashes when attempting to load the .exr file, with the error:

    ModelShowcase/ContentView.swift:169: Fatal error: 'try!' expression unexpectedly raised an error: RealityKit.EnvironmentResource.(unknown context at $22f3b2788).LoadError.resourceNotFound("Lighting.skybox/DaySkyHDRI026A_4K-HDR")

My function is really simple:

func loadHDRiLighting(for arView: ARView, with filename: String) {
    
    let skyboxResource = try! EnvironmentResource.load(named: "Lighting.skybox/\(filename)")
    
    arView.environment.lighting.resource = skyboxResource
    arView.environment.background = .skybox(skyboxResource)
}

I have tried loading the file with, as above, and without the folder name, but the result is the same.

Any clues what could be the reason?


Solution

  • You'll want to put the .exr file in a new folder of the same name with .skybox on the end. Case sensitivity matters in newer versions of Xcode.

    So Lighting.exr should live in Lighting.skybox. The skybox folder should be in the top level of the project.

    The code should look like this:

    func loadHDRiLighting(for arView: ARView, with filename: String) {
        
        let skyboxResource = try! EnvironmentResource.load(named: "Lighting")
        
        arView.environment.lighting.resource = skyboxResource
        arView.environment.background = .skybox(skyboxResource)
    }
    

    Note the .load(named: "Lighting") only has the name of the file, no .exr or .skybox extension.