Architecture#

OneJS connects JavaScript to Unity through several layers.

Architecture Overview#

┌─────────────────────────────────────────────────┐
│                  Your React Code                │
├─────────────────────────────────────────────────┤
│              onejs-react Reconciler             │
├─────────────────────────────────────────────────┤
│           QuickJS JavaScript Engine             │
├─────────────────────────────────────────────────┤
│     QuickJSUIBridge (Events, Scheduling)        │
├─────────────────────────────────────────────────┤
│              UI Toolkit Elements                │
└─────────────────────────────────────────────────┘

The JavaScript Engine#

OneJS uses QuickJS, a small embeddable JavaScript engine. It runs your code in an isolated context with:

  • Full ES2020 support
  • Async/await and Promises
  • ES module source, bundled by esbuild into a single script

QuickJS is interpreted, not JIT-compiled, so it works on iOS and other AOT/IL2CPP platforms where JIT is prohibited. For WebGL builds, OneJS uses the browser's native JavaScript engine instead.

The React Reconciler#

onejs-react is a custom React reconciler. When you write:

<View style={{ padding: 20 }}>
    <Label text="Hello" />
</View>

The reconciler:

  1. Creates a VisualElement for the View
  2. Creates a Label element
  3. Sets the style properties
  4. Adds the Label as a child of the View

React's diffing algorithm handles updates efficiently. Only changed properties are updated.

Component Mapping#

React ComponentUI Toolkit Element
<View>VisualElement
<Text>TextElement
<Label>Label
<Button>Button
<TextField>TextField
<Toggle>Toggle
<Slider>Slider
<ScrollView>ScrollView
<Image>Image
<ListView>ListView
<TreeView>TreeView
<FrostedGlass>FrostedGlassElement
Raw textTextElement

Text handling: Raw text children (e.g., <View>Hello</View>) automatically create TextElement instances. Use <Text> for primary text display and <Label> for form labels.

C# Interop#

The CS global proxy uses reflection to access C# types:

CS.UnityEngine.Debug.Log("Hello")

This resolves to:

  1. Look up the UnityEngine.Debug type
  2. Find the Log method
  3. Convert arguments to C# types
  4. Invoke the method
  5. Convert the return value back to JavaScript

Objects returned from C# are wrapped in proxies with integer handles. Property access and method calls go through the interop layer.

Event System#

UI Toolkit events are captured and routed to JavaScript:

  1. C# registers a TrickleDown callback on the root element
  2. When an event fires, its data is marshaled to JavaScript (pointer events take a zero-allocation fast path)
  3. __dispatchEvent(handle, eventType, data) is called
  4. JavaScript looks up handlers and invokes them
UI Event → C# Capture → Marshal → JS Dispatch → Your Handler

Scheduling#

OneJS provides familiar timing APIs:

  • requestAnimationFrame(): Called every Unity Update
  • setTimeout() / setInterval(): Timer queue processed each frame
  • queueMicrotask(): For Promise resolution

The bridge's Tick() method drives all scheduling from Unity's Update loop.

Memory Management#

C# objects referenced from JavaScript are tracked with integer handles:

  1. C# object → Handle registered in table
  2. JavaScript proxy wraps the handle
  3. When JS object is garbage collected → FinalizationRegistry releases handle
  4. C# object becomes eligible for GC

Manual cleanup is available via releaseObject() (onejs.cs.release() from OneJS 3.9.5) but rarely needed.

Application Lifecycle#

OneJS runs your code in two contexts: edit-mode preview (renders UI without Play mode) and play mode. Export lifecycle hooks to control when game logic runs:

Edit-mode preview:
  InitializeBridge → RunScript (module-level code runs) → EditModeTick at 30Hz

Play mode:
  InitializeBridge → RunScript → onPlay()
  → Update every frame
  → File change → onStop() → teardown → rebuild → onPlay()
  → Exit Play mode → onStop()
  • Module-level code (including render()) runs in both modes, safe for UI
  • onPlay() fires only in play mode, after the bundle loads
  • onStop() fires before teardown (play mode exit or live reload), and when a disabled JSRunner is enabled again, before the fresh context's onPlay()
  • __isPlaying global (onejs.isPlaying from OneJS 3.9.5): true in play mode, false in edit-mode preview

What a hot reload keeps#

A hot reload runs your new code in a fresh JavaScript context, so nothing from the old code keeps running: its timers, subscriptions and C# callbacks are gone, and its useEffect cleanups run first. From OneJS 3.9.17, components keep their state across it:

  • Kept: useState, useReducer and useRef values, in every component that has the same hooks in the same order as before and sits in the same place in the tree. The values reach the new code's first render, so its effects start from them.
  • Started fresh: a component whose hooks you added, removed or reordered, one you renamed or moved, and one whose state holds something that is not plain data, such as a function, a C# object or a class instance. Plain data means numbers, strings, booleans, null, undefined, arrays, plain objects, dates, maps and sets.
  • Never kept: state outside components (module-level variables, stores such as zustand), and UI Toolkit's own state: scroll positions, focus and text selection.

A ref that holds an element or a C# object starts at its initial value, and React fills an element ref again as usual. If the kept state makes the new code throw while it renders, the app renders again from scratch.

The Console line for each reload says what happened, for example [JSRunner] Reloaded (3): kept state in 9 components; 1 started fresh (Inventory: its hooks changed). To start every reload from scratch, turn off Keep Component State in the JSRunner's Project tab.

WebGL Differences#

On WebGL, JavaScript runs in the browser's V8/SpiderMonkey engine:

  • JIT compilation (faster execution)
  • Browser's native RAF loop
  • No QuickJS overhead

The same code runs on both platforms. Only the underlying engine changes.