# Use a Processor in Unity

> Export a Maru Processor, connect gameplay controls and use a watched native development loop in the Unity Editor.

Canonical: https://maru.audio/docs/processor-in-unity
Documentation index: https://maru.audio/llms.txt

A Maru Processor can supply the sound for a Unity AudioSource while Unity
supplies gameplay, scene controls and the audio callback. This tutorial uses
Engine Synth, a procedural car engine, and a three-car showroom.

## Prerequisites and access

Use a **macOS Apple silicon** development machine with **Unity 6**, Xcode
Command Line Tools, **Node.js 24 or later**, and the pnpm version selected by
your Maru checkout. The example and development-session tools described here
are source-checkout tools. You need Maru's native development toolkit and its
Unity integration sources. [Contact Maru](https://maru.audio/contact) for toolkit access and the
matching setup instructions; a browser-only npm installation does not provide
this native build lane. Install the checkout's dependencies using its supplied
instructions and lockfile. Use the bundled ScriptC compiler selected by that
toolkit rather than substituting a compiler from another project.

The tested Editor is Unity 6000.6.12f1 on macOS arm64. Windows, mobile, consoles
and Unity Web need their own builds and host verification. A browser preview
does not establish those targets. Use a separate Unity project for this first
exercise so its scene and audio settings can be inspected without changing a game.

Commands below run from the Maru development checkout's root. They are the
source tools, rather than commands promised by an arbitrary installed CLI version.

For the audio-first authoring loop, the same module can run in the module
workbench while you develop its Processor:

```sh
pnpm module:dev modules/engine-synth --silent
```

The workbench starts muted with this option; enable its output when you want
to listen there, and mute Unity while comparing. Save Processor changes in the
module source rather than copying DSP into a Unity script. Browser face edits
do not replace Unity's schema-generated Inspector or game UI.

## 1. Build the native module

```sh
bash tooling/heavy.sh node --import tsx packages/native-fx-export/game/build.ts modules/engine-synth
bash tooling/heavy.sh python3 packages/native-fx-export/game/verify-engine-synth.py
```

The first command evaluates the module declaration, compiles its canonical
Processor, generates parameter/preset bindings and links the native game C API.
The second silently renders that exact library and checks signal health,
live controls, buffer partitions and basic lifecycle behavior.

The export is under `packages/native-fx-export/game/build/engine-synth/`:

| Output | Purpose |
| --- | --- |
| `Maru-engine-synth-unity.zip` | Unity runtime, bindings, Inspector, native library, importer settings and scene builder |
| `Unity/Assets/Maru` | The same importable assets as an unpacked folder |
| `module.json` and `provenance.json` | Generated schema/preset metadata and native build identity |
| `integration.json` | Exact native library path and byte identity |
| `verification.json` | Native render measurements |

Unity loads compiled native code, not TypeScript, a React face or a VST3.
The generated Inspector comes from the module's schema; the module's browser
face remains a separate consumer of the same controls.

Choose a self-contained stereo Processor for this path. Resource loading,
sidechains, additional buses and full authored-state restoration need their own
host support; native preparation rejects unsupported declarations. A scalar
parameter snapshot is not a saved copy of the Processor's entire DSP state.

## 2. Open the example

```sh
bash tooling/heavy.sh node packages/native-fx-export/game/demo-unity.mjs prepare
```

In Unity Hub, choose **Add project from disk** and select
`packages/native-fx-export/game/build/engine-synth-demo`. Open
`Assets/EngineSynthShowroom.unity`, enter Play mode, select the Game view and
enable **Sound**. Choose Hot hatch, V8 muscle or Turbo boxer rally car. Select
an Exhaust, Engine bay, Cabin or Pass-by camera. Click the Game view for
keyboard input: **W/Up** holds gas, **S/Down** holds brake, **1–3** (including
keypad) selects the primary cars, and **C** changes cameras. The large on-screen
pedals accept the mouse too. Brake overrides gas.

**Space** starts or stops a curved pedal cycle. Adjust its base duration and
pressure/timing variation below the scene; **Tools (F1)** exposes the repeatable
seed, held pedal pressures, gearbox, fixed telemetry and sound parameters.
Choose **Telemetry** in Tools when setting a fixed RPM and speed for a controlled
comparison. **Q/E** selects manual gears, **R** releases pedals, **M** toggles sound
and **Tab** hides the interface. The factory browser exposes the module’s full preset collection. **Auto lap** remains a separate lap driven inside the Processor.

The car buttons apply factory presets. Camera buttons move the visual camera
and set the module's listening perspective. The listener-distance control is
normalized module input, independent of camera world distance. The models stay
parked. Pedals and the curved cycle feed the existing Drive model; RPM, speed
and shifts remain inside the Processor. Auto lap and pass-by sound also run
inside the Processor. The Cabin button selects cabin acoustics with a clear
exterior display angle.

For an existing project, unzip the export and copy its `Maru` folder into
`Assets`. Keep stereo speaker mode and the generated native plugin importer
settings. Add **Maru → Engine Synth** to a GameObject, then add its supplied
Engine Synth Driver. Use one exported Maru project/library containing all the
modules that Unity project needs, rather than overlapping independent exports.
Keep your game scripts and scenes outside the generated `Assets/Maru` folder.
Edit the Processor, schema and presets in their authored module source, rather
than editing generated bindings that the next export will replace. Keep the
exported `.meta` files so scene references retain their stable GUIDs.

## 3. Connect a vehicle controller

In Game mode the game owns RPM, throttle, gear and road speed. Disable the
showroom component when a real vehicle controller drives the same source.
The supplied Engine Synth Driver forwards those values each frame. Speed is
km/h, throttle is 0–1, and the full ranges live in the generated metadata.

For a custom binding, wait until the source is ready, resolve parameter paths
once for that native instance, and check setter return values:

```csharp
using Maru.GameAudio;
using UnityEngine;

// Save as VehicleEngineAudio.cs; use this instead of the demo/driver component.
[RequireComponent(typeof(Maru.GameAudio.Modules.EngineSynthSource))]
public sealed class VehicleEngineAudio : MonoBehaviour
{
    public float engineRpm = 900;
    MaruGameSource audio;
    int rpm = -1;
    void OnEnable() { audio = GetComponent<MaruGameSource>(); rpm = -1; }
    void Update()
    {
        if (!audio.Ready) { rpm = -1; return; }
        if (rpm < 0)
        {
            rpm = audio.ParameterIndex("car.rpm");
            if (rpm < 0 || !audio.SetParameter("drive.mode", 0))
            {
                Debug.LogError("Engine Synth binding failed", this);
                enabled = false;
                return;
            }
        }
        if (!audio.SetParameter(rpm, engineRpm))
            Debug.LogError("RPM was rejected; check the module range", this);
    }
}
```

Make gameplay calls on the main thread. The audio callback only pins Unity's
interleaved stereo buffer and calls the compiled Processor. Parameter values
are physical units, including enum indices. Scalar targets are applied at
bounded processing boundaries; a sequence of setters is not an atomic state
transaction. Smoothing belongs to the Processor.

Rebind cached indices after a new instance or schema import. A removed or renamed
parameter needs a corresponding gameplay change. Exporting a new schema cannot
infer what your game intended to control.

## 4. Watch the Processor while Unity is open

Save the scene and stop Play mode for the first installation, then run this
in another terminal. Once the Editor bridge is installed, use Play mode normally:

```sh
node --import tsx packages/native-fx-export/game/dev-unity.ts \
  --unity-project /absolute/path/to/your/UnityProject \
  modules/engine-synth
```

Do not wrap the long-lived watcher in the heavy command. It acquires resource
admission for each native build and releases it while idle. It uses the same
resolved source-closure owner as the module workbench, including imported DSP
dependencies, instead of recursively watching generated output folders.

The watcher prints a ready revision only after a successful native build,
metadata validation and complete staging. Keep the terminal visible for build
errors. A broken Processor leaves the previous ready revision unchanged.
Save the correction and the watcher builds again. Rapid edits are coalesced;
an edit during compilation supersedes that result before it is handed to Unity.

The first session installs a small Editor bridge and refreshes its generated
shared runtime and Inspector together. This lets an older static export gain
the scalar-capture API before the bridge compiles, while retaining asset GUIDs.
Unity's Auto Refresh can
import it when the Editor regains focus; use **Assets → Refresh** if Auto Refresh
is disabled. Subsequent ready revisions are polled by the bridge, so they do
not depend on switching focus to the Editor.
Select the source component to see its **Native library** binding and frame
counter. A ready terminal build and a running Unity instance are separate
observations: check the imported revision and a progressing frame counter.
Restored live targets take precedence over new defaults. To hear an edited
factory preset, select another car and then select it again. For default-value
changes, stop Play and review the source's saved initial controls. Keep the
inputs fixed when comparing a change to the DSP logic itself.

## 5. Understand the update boundary

Unity's [native-plugin lifecycle](https://docs.unity3d.com/2023.2/Documentation/Manual/PluginInspector.html)
keeps a native library loaded for the Editor session. Replacing a dylib at the
same path does not establish that its new code is executing. This development
loop links a distinct library name for each revision, with Editor-only import
settings. It then:

1. Checks every staged file before writing project assets.
2. Captures scalar parameter targets and supported Maru component settings on
   saved scene objects, then stops Play mode if it is running.
3. Imports the new library and generated bindings with stable script GUIDs.
4. Lets Unity recompile/reload C# and resumes Play mode when it was running.
5. Restores the supported settings while keeping the scene's current references.

This is a short Play-mode restart, not uninterrupted realtime hot swapping.
Oscillator phase, delay/reverb tails, held notes and arbitrary gameplay state
restart. Runtime-spawned objects and custom game-component state need their own
restoration. Save authored scene changes before an update. A failed C# import
needs correction in Unity's Console; native compilation and Editor activation
are separate steps.
The session snapshot is temporary. Record lasting choices in module presets
or save initial Inspector values outside Play mode. It does not write changes
back into module source, save game progress or preserve runtime controls across
an Editor process restart.

Because old libraries remain mapped, restart Unity after eight development
updates. The bridge pauses further imports at that bound. Use **Maru → Development
Session → Pause automatic updates** to pause imports; **Resume automatic updates**
re-enables them, and Ctrl-C stops the watcher. Starting a watcher also re-enables
the session. This is a development convenience,
not a supported player plugin format.

Run one watcher per Unity project. A writer claim in
`Library/MaruProcessorSession.writer/owner.json` records its process and session.
Normal shutdown releases that claim. After a crash, confirm that recorded
process has stopped before moving the abandoned writer folder to the Trash.
Do not clear another running watcher's claim.

## 6. Verify, then make a clean player export

Close the example project before its CLI check, since Unity allows one Editor
process per project:

```sh
bash tooling/heavy.sh node packages/native-fx-export/game/demo-unity.mjs check
```

This runs a bounded Play-mode check using Unity's silent AudioRenderer. It
checks all three car presets and four perspectives, including native parameter
values and finite, non-silent captured output. It does not listen for you or
establish realtime audio-device deadlines.

For a player, stop the watcher and pause its Editor bridge. Close Unity, run
the static build from step 1 again, and replace the development project export
with that clean static `Maru` export. Keep shared runtime and project folders
from the same export. The Editor build guard refuses a player whose generated
bindings still reference a development revision library. Open Unity again and
build the exact player target you intend to ship. Verify sound, live controls,
save/reopen, enable/disable, device changes and performance under graphics load
in that player. A passing Editor capture alone does not establish Mono, IL2CPP
or another platform.

For a first listening comparison, keep car and RPM fixed and switch Exhaust
to Cabin. Then keep the camera fixed and change the car. Those two experiments
separate perspective from engine character before you change the model itself.
