Created
August 4, 2024 11:23
-
-
Save arthurschiller/1bb60b6887a89a9255799f40ce18f694 to your computer and use it in GitHub Desktop.
RealityView Example for accessing scene and subscribing to events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import SwiftUI | |
| import RealityKit | |
| import Combine | |
| struct ContentView: View { | |
| @Environment(\.realityKitScene) var scene: RealityKit.Scene? | |
| @State private var didAddEntitySubscription: Cancellable? | |
| var body: some View { | |
| RealityView { content in | |
| let testEntity = ModelEntity( | |
| mesh: .generateBox(size: 0.25) | |
| ) | |
| testEntity.position = [0, 1.3, -2] | |
| testEntity.name = "testEntity" | |
| content.add(testEntity) | |
| // Below two approaches to subscribe to SceneEvents | |
| // RealityContent Event Subscription approach (wraps combine – no need to store subscription): | |
| let _ = content.subscribe(to: SceneEvents.DidAddEntity.self, on: testEntity) { event in | |
| let entity = event.entity | |
| guard let scene = entity.scene else { | |
| fatalError("Scene should not be nil here.") | |
| } | |
| print("Entity: \(entity.name), scene: \(scene)") | |
| } | |
| // access scene via environment | |
| guard let scene else { | |
| return | |
| } | |
| print("🎉 Scene: \(scene)") | |
| // Combine based subscription approach, need to store it: | |
| didAddEntitySubscription = scene.subscribe(to: SceneEvents.DidAddEntity.self, on: testEntity) { event in | |
| let entity = event.entity | |
| guard let scene = entity.scene else { | |
| fatalError("Scene should not be nil here.") | |
| } | |
| print("Entity: \(entity.name), scene: \(scene)") | |
| } | |
| // to cancel it do: didAddEntitySubscription.cancel() | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment