Sending one Notification to trigger multiple Behaviors

We can trigger more than one Behavior/Timeline using a single notification, even when the timelines are defined in different files.

Let’s load a scene and send a simple notification from code.

struct Example123: View {

    @Environment(\.realityKitScene) var scene
    
    var body: some View {
        RealityView { content in
            guard let scene = try? await Entity(named: "SharedNotification", in: realityKitContentBundle) else { return }
            scene.position.y = -0.4
            content.add(scene)
        }
        .toolbar {
            ToolbarItem(placement: .bottomOrnament, content: {
                Button(action: {
                    notifyTimeline("RunTimelines")
                }, label: {
                    Text("Send")
                })
            })
        }
    }
    func notifyTimeline(_ identifier: String) {
        if let scene = scene {
            NotificationCenter.default.post(
                name: NSNotification.Name("RealityKit.NotificationTrigger"),
                object: nil,
                userInfo: [
                    "RealityKit.NotificationTrigger.Scene": scene,
                    "RealityKit.NotificationTrigger.Identifier": identifier
                ]
            )
        }
    }
}

In Reality Composer Pro we’ll add two scenes. One called SharedNotification and one called SharedNotificationChild. In the child scene we’ll add a Rocket and timeline that runs when we receive the notification.

An entity with a timeline and behavior in a child scene

Then we can drop that scene into the other one as a reference. Notice that the Timelines section shows the Rocket Timeline from the child scene. We’ll also add timelines and behaviors for some other entities in this scene. All behaviors share the same trigger. They will run when receiving the notification named RunTimelines.

Parent scene with several timelines and behaviors

When we send the notification all timelines will run at the same time. This can make it easy to break complex entities into small files and later compose them together in a single scene.

Demo: sending one notification to trigger multiple behaviors

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?