RealityKit Basics: using realityKitScene Environment Variable
We can access the RealityKit Scene of the nearest RealityView.
Overview
We can import this environment variable to access a Scene from outside of a RealityView.
@Environment(\.realityKitScene) var realityKitSceneThis is not the same thing as using content (or RealityViewContent). This Scene gives access to methods that find entities by name or id, query sets of entities, subscribe to events, and convert between coordinate spaces.
It seems like this Scene is more related to ARKit on iOS than visionOS development.
This isn’t something we use often, but it is there if we need it. A couple of examples:
// access the scene and find a specific entity
if let earth = realityKitScene?.findEntity(named: "Earth") {
earth.orientation *= simd_quatf(angle: .pi/2, axis: [0,1,0])
}// access the scene and query all entities that have a given component
guard let scene = realityKitScene else { return }
let query = EntityQuery(where: .has(ModelComponent.self))
let enumerated = scene.performQuery(query).enumerated()
print("Entities in scene:", enumerated)If you’re using this in visionOS apps, we would love to hear about your use case. Leave a comment or stop by Office Hours to let us know.
Example Code
struct Example133: View {
@Environment(\.realityKitScene) var realityKitScene
@State var earthString: String = ""
var body: some View {
RealityView { content in
guard let scene = try? await Entity(named: "Earth", in: realityKitContentBundle) else { return }
scene.name = "Earth"
content.add(scene)
}
.toolbar {
ToolbarItem(placement: .bottomOrnament, content: {
HStack {
// Example 01 - find and update an entity
Button(action: {
if let earth = realityKitScene?.findEntity(named: "Earth") {
earth.orientation *= simd_quatf(angle: .pi/2, axis: [0,1,0])
}
}, label: {
Image(systemName: "arrow.left")
})
Button(action: {
if let earth = realityKitScene?.findEntity(named: "Earth") {
earth.orientation *= simd_quatf(angle: .pi/2, axis: [0,-1,0])
}
}, label: {
Image(systemName: "arrow.right")
})
// Example 02 - query the entities in the scene
Button(action: {
guard let scene = realityKitScene else { return }
let query = EntityQuery(where: .has(ModelComponent.self))
let enumerated = scene.performQuery(query).enumerated()
print("Entities in scene:", enumerated)
}, label: {
Text("Print Entities")
})
}
})
}
}
}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.

Follow Step Into Vision