How to pass a value when opening an immersive space

Just like with Windows and Volumes, we can pass a value when opening an Immersive Space.

This is useful when have multiple scenes in our RealityKitContent but want to use shared SwiftUI/RealityKit code.

In the Immersive Space view, add a binding with the type our view needs. In this example I just used string.

struct ImmersiveView: View {
  @Binding var sceneName: String?
  ...
}

In the App file, we can update or call to ImmersiveSpace to use this version.

struct Garden15App: App {

    @State private var appModel = AppModel()

    var body: some Scene {
        ...
        ImmersiveSpace(id: "Bubble Garden", for: String.self, content: { $value in
            ImmersiveView(sceneName: $value)
                .environment(appModel)
        })
     }
}

When we tap on the button to open a scene, we can pass the new value.

await openImmersiveSpace(id: "Bubble Garden", value: "Red")

In this example I used these concepts to open three different scenes from the RealityKitContent.

Switch between three visionOS immersive scenes called Red, Green, and Blue.

Sample code is available in Garden15 in the Step Into Example Projects repo.

Support our work so we can continue to bring you new examples and articles.

Download the Xcode project with this and many more examples from Step Into Vision.
Some examples are provided as standalone Xcode projects. You can find those here.

Questions or feedback?