Sample CodevisionOSReviewed 2026-11-01View on Apple Developer

Designing no-code games with Reality Composer Pro 3

At a glance

Item Summary
Purpose Ship a platformer whose gameplay is authored entirely as Reality Composer Pro Script Graphs; the Swift app only loads the scene, hosts SwiftUI attachments, and relays named scene events in both directions.
App architecture One visionOS app target. SquirrelApp sets up the ScriptingRuntime and opens a volumetric window. ContentView loads the world entity, parents attachment views to anchor entities authored in the scene, subscribes to graph-raised events, and sends UI events back with scene.send(name:).
Main patterns Binding-based state propagation (attachment buttons write ContentView state through bindings)
Project style A flat Squirrel/ source folder (app, root view, attachment views, previews), a Reality Composer Pro project plus its exported Scenes.reality under Data/, and helper shell scripts under Configuration/.
Execution model The target defaults to main-actor isolation. Scene-event callbacks hop with DispatchQueue.main.async before writing @State. One Task { @MainActor in } delays enabling the character. Subscriptions are retained in a @State array of AnyCancellable.
State/event model String-named scene events from Script Graphs into SwiftUI @State; SwiftUI values and closures passed into attachment views; named events (some with arguments) sent from SwiftUI back to the graphs.
Key frameworks/packages Swift modules SwiftUI, RealityKit, RealityKitScripting, Combine, os; RealityKitScripting comes from the remote realitykitscripting package.

Project structure

Squirrel.xcodeproj               # 1 app target, xros only
Squirrel/                        # synchronized app folder
├── SquirrelApp.swift            # @main, ScriptingRuntime.setup, volumetric window
├── ContentView.swift            # RealityView, event bridge, send helpers
├── ContentViewAttachments.swift # StartButtonAttachment, EndScreenAttachment, OrnamentBar
├── SquirrelTalkAttachmentView.swift
├── DinnerBubbleView.swift       # TreeTalkAttachmentView, SpeechBubbleShape
├── UIPreview.swift              # #Preview only
└── Info.plist                   # volumetric default scene role
Data/
├── Squirrel.realitycomposerpro/ # RCP project: scenes, Script Graphs, event library
└── RealityFiles/Scenes.reality  # exported scene bundled as a resource
Configuration/                   # SampleCode.xcconfig + RCP helper scripts

Structure observations

  • The project has one application target (Squirrel.xcodeproj/project.pbxproj:119) restricted to xros xrsimulator (Squirrel.xcodeproj/project.pbxproj:332). Its only package product is RealityKitScripting (Squirrel.xcodeproj/project.pbxproj:115).
  • The exported Data/RealityFiles/Scenes.reality is copied into the app as a resource (Squirrel.xcodeproj/project.pbxproj:11). Gameplay lives in that asset, not in Swift: the app has six Swift files, and only ContentView.swift touches RealityKit.
  • The target’s build phases are only Sources, Frameworks, and Resources (Squirrel.xcodeproj/project.pbxproj:104). The Configuration/*.sh scripts are not build phases; for example ExportRealityFiles.sh runs Reality Composer Pro headless to regenerate RealityFiles (Configuration/ExportRealityFiles.sh:22).
  • Info.plist makes the volumetric window the default scene role (Squirrel/Info.plist:8).

Overall architecture

Reference code

Squirrel/SquirrelApp.swift:25 — the runtime is set up before any scene loads

@main
struct SquirrelApp: App {

    init() {
        // Set up the Script Graph runtime before any RealityView loads
        // a scene that contains `ScriptingComponent`s. `.subtracting(.ar)`
        // disables AR input because this sample runs in a volumetric window.
        ScriptingRuntime.setup(inputOptions: .all.subtracting(.ar))
    }

    var body: some SwiftUI.Scene {
        WindowGroup {
            ContentView()
        }
        #if os(visionOS)
            .windowStyle(.volumetric)
            .defaultSize(width: 1.8, height: 1.8, depth: 1.2, in: .meters)
        #endif
    }
}

Squirrel/ContentView.swift:291 — SwiftUI-to-graph direction

    private func sendSceneEvent(eventName: String) {
        guard let scene = self.scene?.scene else {
            return
        }
        scene.send(name: eventName)
    }

Interpretation

Observed: the Swift code never moves the character or evaluates game rules. It loads the scene (Squirrel/ContentView.swift:42), enables scripting input on the view (Squirrel/ContentView.swift:264), listens for eight named events (Squirrel/ContentView.swift:110 through Squirrel/ContentView.swift:182), and sends names such as revealStage, startGame, restartGame, resetCharacter, and setCurrentLevelScreen (Squirrel/ContentView.swift:217, Squirrel/ContentView.swift:248, Squirrel/ContentView.swift:257, Squirrel/ContentView.swift:305).

Inference: the event names form the contract between the no-code game and the app. Designers can change gameplay in the graphs freely, as long as the named events and their argument keys (sayThis, levelScreenName) stay stable.

Ownership and state

Ownership evidence

Squirrel/ContentView.swift:14 — the root view owns the scene, the subscriptions, and all game-UI state

struct ContentView: View {
    @State var error: String?
    @State var scene: Entity?
    @State var cancellables: [AnyCancellable] = []
    // ...
    @State var showStartButton: Bool = false
    // ...
    @State var showOrnament: Bool = false
    // ...
    @State var playStartTime: Date? = nil // Track when gameplay started
    @State var playTime: TimeInterval = 0 // Track total play time
    @State var showRevealButton: Bool = true
    // ...
}
Owner Object or state Relationship Mutation authority
ContentView scene: Entity? @State, assigned after the async load (Squirrel/ContentView.swift:53) Only the RealityView make closure
ContentView cancellables: [AnyCancellable] @State; each scene subscription is stored with .store(in: &cancellables) (Squirrel/ContentView.swift:120) The DidAddEntity handler, once
ContentView Speech text and triggers, bubble flags, ornament flag, play timing @State (Squirrel/ContentView.swift:19 through Squirrel/ContentView.swift:33) Event callbacks on the main queue; attachment views through bindings
StartButtonAttachment showStartButton, playStartTime, playTime @Binding into ContentView state (Squirrel/ContentViewAttachments.swift:11) Its button resets them and calls onStart
EndScreenAttachment showEndScreen @Binding (Squirrel/ContentViewAttachments.swift:38) Its Play Again button
SquirrelTalkAttachmentView displayedText, scale, isVisible private @State (Squirrel/SquirrelTalkAttachmentView.swift:18) The view, reacting to trigger/endTrigger changes
Reality Composer Pro scene Game state (levels, character, nut) Inside Script Graphs; not visible in Swift Graphs, driven by sent events

GameUIState and BubbleState in the diagram stand for the groups of @State properties in the table. Attachment entities are parented to anchor entities authored in the scene (SquirrelAttachmentEntity, TreeAttachmentEntity) so the graph controls their placement (Squirrel/ContentView.swift:58, Squirrel/ContentView.swift:67).

Concurrency, scheduling, and thread safety

Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution. A Sendable conformance alone does not prove thread-safe mutation.

Concern Source mechanism Verified placement or handoff Evidence
Main-actor isolation (target-wide) SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor Views and helpers without explicit isolation are main-actor isolated. Squirrel.xcodeproj/project.pbxproj:334
Async scene load try await Entity(named: "world") Suspends inside the RealityView make closure; the result is added to content and stored in scene. Squirrel/ContentView.swift:42
One-shot event content.subscribe(to: SceneEvents.DidAddEntity.self, on: entity) Waits until entity.scene exists, registers all named-event subscriptions, then cancels itself. Squirrel/ContentView.swift:98, Squirrel/ContentView.swift:189
Main-queue scheduling DispatchQueue.main.async Every named-event callback submits its @State writes to the main queue. The source does not state which context invokes the callback. Squirrel/ContentView.swift:112, Squirrel/ContentView.swift:136, Squirrel/ContentView.swift:183
Subscription lifetime AnyCancellable stored in @State Retained for the view’s lifetime; never cancelled explicitly. Squirrel/ContentView.swift:17, Squirrel/ContentView.swift:120
Task creation Task { @MainActor in } + Task.sleep(for: .seconds(2)) Re-enables the Character entity after a delay; not retained or cancelled. Squirrel/ContentView.swift:196
Task creation Plain Task { onStart() } / Task { onRestart() } Defers the send callback from attachment buttons; inherits the main actor; not retained. Squirrel/ContentViewAttachments.swift:22, Squirrel/ContentViewAttachments.swift:55

No lock, actor declaration, or background queue appears in the source.

Reference code

Squirrel/ContentView.swift:110 — a graph event becomes SwiftUI state on the main queue

                    scene.subscribe(to: "squirrelTalk", { event in
                        if let sayThis: String = try? event.value("sayThis") {
                            DispatchQueue.main.async {
                                if sayThis == "zzz" {
                                    self.showSquirrelTalk = true
                                }
                                self.squirrelTalkText = sayThis
                                self.squirrelTalkTrigger += 1
                            }
                        }
                    }).store(in: &cancellables)

Squirrel/ContentView.swift:194 — a delayed enable gives graphs time to compile

                if let character = entity.findEntity(named: "Character") {
                    character.isEnabled = false
                    Task { @MainActor in
                        try? await Task.sleep(for: .seconds(2))
                        character.isEnabled = true
                    }
                }

Inference: the squirrelTalkTrigger/squirrelTalkEndTrigger counters exist because the same line of text can arrive twice; incrementing a counter guarantees an onChange in SquirrelTalkAttachmentView even when the string is unchanged (Squirrel/SquirrelTalkAttachmentView.swift:48). The source comment calls it a “Trigger counter to force updates” (Squirrel/ContentView.swift:24).

State propagation, frameworks, and dependencies

Evidence limit: an import proves a source-level compilation dependency at the cited line. It does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.

Category Mechanism or module Verified role Evidence
Graph to app scene.subscribe(to:_:) with event.value("sayThis") Named events with typed payloads update @State Squirrel/ContentView.swift:110, Squirrel/ContentView.swift:111
App to graph scene.send(name:), scene.send(name:arguments:) UI actions become graph events Squirrel/ContentView.swift:295, Squirrel/ContentView.swift:305
Scripting input .enableRealityKitScriptingInput() Connects the view to the runtime set up in SquirrelApp Squirrel/ContentView.swift:264
SwiftUI propagation Value parameters and closures SquirrelTalkAttachmentView, TreeTalkAttachmentView, and OrnamentBar receive let values and callbacks Squirrel/ContentView.swift:228, Squirrel/ContentView.swift:270
SwiftUI propagation @Binding Start and end attachments write back to ContentView state Squirrel/ContentView.swift:245, Squirrel/ContentViewAttachments.swift:11
Swift module import RealityKitScripting, RealityKit, SwiftUI Scripting runtime and scene APIs; UI Squirrel/ContentView.swift:9, Squirrel/ContentView.swift:8, Squirrel/ContentView.swift:10
Swift module import Combine Supplies AnyCancellable storage only; no publisher pipeline or scheduling operator appears Squirrel/ContentView.swift:11
Swift module import os File-scope Logger used for warnings Squirrel/SquirrelApp.swift:11, Squirrel/SquirrelApp.swift:15
Package declaration Remote realitykitscripting (from 1.4.0), product RealityKitScripting Direct package dependency of the app target Squirrel.xcodeproj/project.pbxproj:402, Squirrel.xcodeproj/project.pbxproj:405

Class and protocol design

Reference code

Squirrel/ContentViewAttachments.swift:72 — a stateless view that reports intent through closures

struct OrnamentBar: View {
    let showOrnament: Bool
    let showStartButton: Bool
    let onSceneEvent: (String) -> Void
    let onJumpToScene: (String) -> Void
    // ...
}
Type Responsibility Depends on
SquirrelApp Runtime setup, volumetric window ScriptingRuntime, ContentView
ContentView Scene load, attachment placement, event bridge, send helpers, play timing RealityView, RealityKitScripting
StartButtonAttachment, EndScreenAttachment Start and end UI; write bindings and call one closure —
OrnamentBar Debug/game controls: reset, restart section, grab nut, jump to level Closures only
SquirrelTalkAttachmentView, TreeTalkAttachmentView Speech bubbles animated from passed values SpeechBubbleShape
SpeechBubbleShape Custom InsettableShape —
scriptingEntity(_:) Free function that walks up to the nearest entity with a ScriptingComponent ScriptingComponent

All conformances are to framework protocols. scriptingEntity(_:) is declared at file scope but has no caller in the Swift source (Squirrel/ContentView.swift:327).

Access control

Symbol Access Verified effect Likely rationale
ContentView.sendSceneEvent(eventName:), jumpToScene(sceneName:), formatPlayTime(_:) private Callable only within ContentView’s file; attachments receive them as closure values (Squirrel/ContentView.swift:291, Squirrel/ContentView.swift:301, Squirrel/ContentView.swift:309). Inference: only ContentView holds the scene reference, so only it can send events; children get capability, not the scene.
SquirrelTalkAttachmentView bubble state private @State Only the bubble view animates itself (Squirrel/SquirrelTalkAttachmentView.swift:18). Inference: animation state stays local to the presentation.
OrnamentBar.levelSwitches private static let Level names are visible only to the ornament (Squirrel/ContentViewAttachments.swift:78). Inference: the level list is UI configuration.
ContentView @State properties implicitly internal Not marked private, so other code in the module could name them; in practice only ContentView and its bindings write them (Squirrel/ContentView.swift:15). —

logger is a module-wide, implicitly internal constant (Squirrel/SquirrelApp.swift:15). Nothing is public or open.

Reference code

Squirrel/ContentView.swift:301 — a private helper that sends an event with arguments

    private func jumpToScene(sceneName: String) {
        guard let scene = self.scene?.scene else {
            return
        }
        scene.send(name: "setCurrentLevelScreen", arguments: ["levelScreenName": sceneName])
        scene.send(name: "resetCharacter")
    }

Logic ownership and placement

Logic Owning type or file Placement rationale
Gameplay, level flow, character and nut behavior Reality Composer Pro Script Graphs (bundled Scenes.reality) Observed: no gameplay code in Swift; the app sends and receives named events only.
Event-to-UI mapping ContentView subscription closures Observed: each event updates specific @State values (Squirrel/ContentView.swift:149).
Play-time measurement StartButtonAttachment (start) and the endGameUI handler (stop) Observed: start sets playStartTime = Date() (Squirrel/ContentViewAttachments.swift:20); endGameUI computes playTime (Squirrel/ContentView.swift:152).
Attachment placement ContentView make closure Observed: attachments are parented to scene-authored anchor entities or added at fixed positions (Squirrel/ContentView.swift:62, Squirrel/ContentView.swift:77).
Bloom post-processing ContentView make closure Observed: BloomComponent and BloomOptionsComponent are set on the root entity (Squirrel/ContentView.swift:43).
Scene export Configuration/ExportRealityFiles.sh Observed: a developer-run script, outside the build.

Design patterns

Pattern Source evidence Purpose or tradeoff
Binding-based state propagation Squirrel/ContentView.swift:245 ($showStartButton, $playStartTime, $playTime) into Squirrel/ContentViewAttachments.swift:11 Attachment views edit state that ContentView owns, so the event handlers and the buttons share one source of truth.

The Script Graph event bridge is the sample’s central collaboration, but it is a framework messaging API (named events with a subscription and a send) rather than a separately named design pattern in source, so no further label is claimed.

Naming conventions

  • Types: …App for the entry, …View/…AttachmentView for SwiftUI views placed as RealityView attachments, …Attachment for attachment-only UI (StartButtonAttachment, EndScreenAttachment), …Bar for the ornament, …Shape for the custom shape. DinnerBubbleView.swift contains TreeTalkAttachmentView, so this file name does not match its type.
  • Attachment IDs are kebab case ("squirrel-talk", "tree-talk", "start-button", "end-screen", "loading-reveal").
  • Scene event names are lower camel case verbs or phrases (revealStage, startGame, resetNut, showOrnament, endGameUI); payload keys are lower camel case (sayThis, levelScreenName).
  • Scene entity names are upper camel case and suffixed by role (SquirrelAttachmentEntity, TreeAttachmentEntity, Character).
  • Callback parameters use the on… prefix (onStart, onRestart, onSceneEvent, onJumpToScene).

Architecture takeaways

  • Put gameplay in authored content and keep the Swift layer as a thin host: load, place UI, translate events. The contract is a short list of event names and payload keys.
  • Hand child views closures (onSceneEvent) rather than the scene entity, so only one view can talk to the runtime.
  • Store scene subscriptions in owned state ([AnyCancellable]), and use a one-shot DidAddEntity subscription to wait until the scene exists before subscribing.
  • Use a counter trigger when the same value can repeat and the UI must still react.
  • Event callbacks hop to the main queue before mutating SwiftUI state; the source does not rely on the callback’s own context.

Source map

Source file Relevant symbols
Squirrel/SquirrelApp.swift SquirrelApp, ScriptingRuntime.setup, logger
Squirrel/ContentView.swift ContentView, event subscriptions, sendSceneEvent, jumpToScene, formatPlayTime, scriptingEntity(_:)
Squirrel/ContentViewAttachments.swift StartButtonAttachment, EndScreenAttachment, OrnamentBar
Squirrel/SquirrelTalkAttachmentView.swift SquirrelTalkAttachmentView
Squirrel/DinnerBubbleView.swift TreeTalkAttachmentView, SpeechBubbleShape
Squirrel/Info.plist Volumetric default scene role
Squirrel.xcodeproj/project.pbxproj Target, default isolation, Scenes.reality resource, RealityKitScripting package
Configuration/ExportRealityFiles.sh Headless Reality Composer Pro export