by Pivec Labs
Tutorial Multiplayer VR

NetCrafter Relay — VR Tutorial

Build a host-relayed multiplayer VR experience — tracked head/hand sync, world-space UI, on top of OpenWorlds VR for Unity Third Person.

By Pivec Labs

Time: 120–150 minutes
Prerequisites: NetCrafter Relay installed; your own self-hosted coturn + rendezvous instance up and running (see the Server Deployment Guide); Allow downloads over HTTP set to Always allowed in Player Settings (Edit → Project Settings → Player → Other Settings → Configuration — a fresh project defaults to blocking this, which fails the very first connection attempt with InvalidOperationException: Insecure connection not allowed; see Getting Started); Unity's Input System package active (Edit → Project Settings → Player → Active Input Handling set to Input System Package or Both — this project ships set to Input System Package); TextMeshPro essentials imported (Window → TextMeshPro → Import TMP Essentials); OpenWorlds VR for Unity Third Person, version 1.3.2 or higher, imported from the Unity Asset Store; a compatible XR headset and OpenXR runtime for actually testing in a headset (a desktop fallback mode is covered in Part 1, but this tutorial's VR-specific behaviour is only meaningfully testable on real hardware). Recommended (not required): read the Chat Quick Start and Animated Multiplayer Character tutorials first — this tutorial reuses their Login/Lobby flow and sync-system concepts without re-explaining them from scratch.

What you'll build: A shared VR space where every connected player sees everyone else's head and hands tracked live — host-relayed, 2-4 players, world-space UI (there's no desktop screen to put a Screen Space Overlay canvas on when you're wearing a headset). OpenWorlds VR for Third Person supplies the XR rig, avatar IK, and hand tracking; NetCrafter Relay supplies the networking. This is the only NetCrafter Relay tutorial that depends on a second paid, same-studio asset — see Part 0 for exactly what that means for what ships where.

This tutorial is experimental. VR support for Relay is newer and far less battle-tested than the rest of this package (Chat, Co-op, Character, Racing) — it works, and the reference implementation here is a real, working demo, but it hasn't been through the same depth of real-world testing those have. If you're building a major/production VR project, use NetCrafter Pro for SFS3 instead — its VR support is mature and proven. Treat this tutorial as a working starting point for smaller projects or your own experimentation, not yet as a production-hardened path.

01

Part 0 — What's different about this tutorial#

Like every other NetCrafter Relay tutorial, this one is Login → Lobby (real join code, Host/Join) → Gameplay, built on RelayConnectionManager, NetCrafterEventDispatcher, Scene Events, and NetCrafterSyncBinding. Four things are genuinely new:

  1. World-space UI, not Screen Space Overlay. Chat/Co-op/Character/Racing all use an ordinary screen-space canvas, because every one of them is played on a monitor. A player wearing a headset has no monitor to overlay onto — the Login/Lobby/Gameplay canvas in this tutorial is a world-space Canvas, placed a short distance in front of wherever the player starts, sized and scaled for a comfortable reading distance in VR. See Part 7.
  2. OpenWorlds VR for Unity Third Person is a second paid Pivec Labs asset, not a bundled dependency. It is sold separately, is not free, and this package does not — and cannot — ship any of its content. This isn't a licensing technicality this tutorial works around; it's the same relationship NetCrafter Relay itself has to NetCrafter (its SFS3 sibling) — two independent products, each useful on its own, that happen to combine well. Concretely: the schema, the generated networking code, VRDemoController.cs, and the small helper scripts (VRColorManager, PlayerNameDisplay, RemoteAnimationEventReceiver, RemoteVRCharacterController) all ship and all compile with or without OpenWorlds VR imported. The parts that only make sense with it — the XR rig, the tracked player prefab, the remote-avatar prefab's IK wiring — are things you build in your own project, following Part 1 and Part 7 below. A scripting define, NETCRAFTER_VR_EXAMPLE, gates the handful of lines that touch real OpenWorlds VR types; without it defined, the demo still compiles and the Lobby/Login flow still works, it just has no VR player to configure (see Part 7.7 and Common Mistakes).
  3. Head/hand pose rides NetCrafter Relay's own sync rules directly, in world space — not a manually-packed relative-position message. Every tracked point (root, head, left hand, right hand) gets its own Transform_Position + Transform_Rotation sync rule, applied by NetCrafterSyncBinding exactly like Character's or Racing's transform sync — because NetCrafterSyncBinding already reads and writes Transform.position/Transform.rotation in world space, a small child GameObject sitting wherever the tracked point actually is just works, with no relative-math reconstruction needed on either end. That's 8 sync rules total (4 tracked points × position + rotation) — see Part 6.
  4. Locomotion state and desktop-mode are messages, not sync rules, because there's no integer sync target. NetCrafterSyncBinding supports Animator_Float and Animator_Bool, not Animator_Int, and the OpenWorlds VR animator drives locomotion off a set of mutually-exclusive direction bools (WalkForward, RunLeft, InAir, …) rather than a blend-tree float. Rather than stretch the sync system to fit, this tutorial packs those bools into one wire-friendly animState int (0–10) and sends it, along with grounded and isDesktopMode, as an edge-triggered RequestPlayerStatus/PlayerStatusUpdate message pair — only when something actually changes, not on a fixed per-frame cadence. See Part 3.4 and Part 4.2.

Scope, stated plainly: host-relay-only star topology (joiners never talk to each other directly, only through whichever client is hosting), 2-4 players; a player who quits is noticed at once, one who crashes after ~15 seconds of silence. If the host disconnects, there is no migration — remaining joiners see a clear status message and that session is over, same as every other tutorial in this package.

02

Part 1 — Local VR setup (no networking yet)#

This part has nothing to do with NetCrafter Relay — it gets one local player walking around in VR, with OpenWorlds VR's own rig and IK working, entirely offline. This tutorial cannot give you OpenWorlds VR's own setup steps verbatim — that asset's own documentation is the source of truth for its XR rig, sample scene, and character-selection flow, and it may change between versions. What follows is what this tutorial's own networking code needs to find once you're done with that setup — treat it as a checklist to confirm against OpenWorlds VR's own instructions, not a replacement for them.

1.1 Import OpenWorlds VR for Unity Third Person

  1. Get OpenWorlds VR for Unity Third Person, version 1.3.2 or higher, from the Unity Asset Store. Import it via Package Manager → My Assets, same as any other Asset Store package.
  2. Importing it will pull in its own package dependencies through Unity's Package Manager (confirmed at the version this tutorial was written against: XR Interaction Toolkit, XR Plugin Management, OpenXR Plugin, Cinemachine, and the Input System package) — let Package Manager resolve these automatically rather than installing them separately first.
  3. Follow OpenWorlds VR's own documentation to get its sample/demo scene running with one local player: character selection, the XR rig, hand tracking. Confirm you can see your own avatar's head and hands move with your headset and controllers before moving on — that's the point at which OpenWorldsVRManager.Instance.player becomes non-null, which is where this tutorial's own code starts caring.
  4. Desktop fallback mode. This tutorial's networking code checks OpenWorldsVRManager.Instance.isHeadsetOffHead (and a direct XR head-node validity check) to decide whether a player is actually wearing a headset — this is the isDesktopMode flag in Part 3.4. You can exercise the Login/Lobby UI and the networking flow with the headset off, but you won't see tracked head/hand movement without one.

1.2 Confirm the three scene singletons

Once a local player is active, confirm HeadFollower, LHandFollower, and RHandFollower components exist somewhere in the scene (they're scene-level singletons, not children of the player object — OpenWorlds VR activates them once the player is assigned). Part 7 attaches NetCrafterSyncBinding components directly to these three objects — if you can't find them, something about Part 1.3's setup didn't complete, not a NetCrafter Relay problem.

1.3 Import NetCrafter Relay

If you haven't already, import the NetCrafter Relay package into this project (Assets → Import Package → Custom Package…, or however you obtained it from the Asset Store). Confirm Assets/PivecLabs/NetCrafterRelay/ exists in the Project window afterward.

Everything above this line is entirely OpenWorlds-VR-specific, not a NetCrafter Relay concern. If you already have a local VR player walking around with working head/hand tracking, there was nothing relay-specific to change here. The interesting part starts now.

03

Part 2 — Create the schema#

Tools → Pivec Labs → NetCrafter Relay. Click + Create Definition, enter VRDemo, click Create.

This tutorial's own shipped schema (Definitions/VRDemo/) was built exactly this way, through the real editor tabs — nothing in it is hand-typed text pretending to be generated output. You can use the shipped one directly and skip to Part 7, or delete it and rebuild it yourself by following Parts 2–6 to learn the system firsthand — both paths produce the same result.

04

Part 3 — Define the messages#

Open the Gameplay Messages tab. Create the following five.

3.1 Login — client tells the host its display name

FieldValue
Message NameLogin
DirectionClientToHost
TransportReliable
Host Handler NameHandleLogin

Add one field: displayName (type string).

3.2 PlayerJoined — host announces a player (new or already-known) to someone

FieldValue
Message NamePlayerJoined
DirectionHostToClient
TransportReliable
Host Handler Name(leave blank)

Add four fields: playerId (int), displayName (string), colorIndex (int), spawnIndex (int). Same pattern as Character/Racing — colorIndex/spawnIndex are computed host-side from senderId (Part 4.1), never trusted from the joining client.

3.3 PlayerLeft — host announces a player disconnected

FieldValue
Message NamePlayerLeft
DirectionHostToClient
TransportReliable
Host Handler Name(leave blank)

Add one field: playerId (int).

Only covers a joiner disconnecting — the host detects it (OnPeerDisconnected: at once for a normal quit, ~15s of silence for a crash) and broadcasts this message to everyone else. If the host itself disconnects, each remaining joiner detects that independently and locally — see Part 7.7.

3.4 RequestPlayerStatus — a joiner's locomotion/grounded/desktop-mode state changed

FieldValue
Message NameRequestPlayerStatus
DirectionClientToHost
TransportReliable
Host Handler NameHandlePlayerStatus

Add three fields: animState (int), grounded (bool), isDesktopMode (bool).

animState is a single wire-friendly int (0–10) standing in for OpenWorlds VR's mutually-exclusive locomotion bools, since there's no Animator_Int sync target:

animStateMeaning
0Idle
1WalkForward
2WalkBackward
3WalkLeft
4WalkRight
5RunForward
6RunBackward
7RunLeft
8RunRight
9InAir
10JumpLand

3.5 PlayerStatusUpdate — host's broadcast of a player's locomotion/grounded/desktop-mode state

FieldValue
Message NamePlayerStatusUpdate
DirectionHostToClient
TransportReliable
Host Handler Name(leave blank)

Add four fields: playerId (int), animState (int), grounded (bool), isDesktopMode (bool).

There's no message here for head/hand/root position or rotation — those replicate through the sync system (Part 6), sent at most 20 times a second each (see the interval discussion there). The two messages above are edge-triggered — sent only when animState/grounded/isDesktopMode actually change, polled locally every 0.1s — not on a fixed per-frame cadence, which matters a lot more here than in Chat/Co-op since a VR session already has eight continuous sync rules running per remote player.

05

Part 4 — Define the Host Actions#

Open the Host Actions tab. Create two.

4.1 HandleLogin

FieldValue
Handler NameHandleLogin
Trigger MessageLogin
Response EventPlayerJoined
Logic TypeCustom

Custom Host Code (the same roster-replay pattern as every other tutorial's HandleLogin — see the Character or Racing tutorial for the full explanation of why the replay loop exists):

C#
string displayName = trigger.displayName;
int colorIndex = senderId % 8;
int spawnIndex = senderId % 4;

foreach (var kv in VRGameState.Players)
{
    var existing = new PlayerJoinedEvent {
        playerId = kv.Key, displayName = kv.Value.displayName,
        colorIndex = kv.Value.colorIndex, spawnIndex = kv.Value.spawnIndex
    };
    connection.SendToPeer(senderId, "PlayerJoined", existing.Serialize(), true);
}

VRGameState.Players[senderId] = new VRGameState.PlayerInfo {
    displayName = displayName, colorIndex = colorIndex, spawnIndex = spawnIndex
};
var joined = new PlayerJoinedEvent {
    playerId = senderId, displayName = displayName, colorIndex = colorIndex, spawnIndex = spawnIndex
};
connection.BroadcastToAll("PlayerJoined", joined.Serialize(), true);

// BroadcastToAll never loops back to the host's own incoming-message pipeline, so without
// this direct call the HOST never registers a newly-joined player locally.
VRDemoController.Instance?.HostRegisterPlayerLocally(senderId, displayName, colorIndex, spawnIndex);

Logic Type must actually be set to Custom, or this code is silently ignored — confirmed the hard way while building this tutorial. BroadcastAll/SenderOnly/TargetUser are fixed, hardcoded response templates that never look at the Custom Host Code field at all, even if it isn't empty — there's no error, no warning, the generated output simply doesn't contain it. If your generated HostActionRouter.cs is missing a Host Action's custom logic entirely (not just auto-matched fields), this is the first thing to check. See Common Mistakes.

4.2 HandlePlayerStatus

FieldValue
Handler NameHandlePlayerStatus
Trigger MessageRequestPlayerStatus
Response EventPlayerStatusUpdate
Logic TypeBroadcastAll

Leave Custom Host Code blank. This is the first Host Action in any NetCrafter Relay tutorial that needs none at all: every response field name (animState, grounded, isDesktopMode) matches a trigger field name exactly, and the generator auto-fills response.playerId = senderId as a special case on top of that — so BroadcastAll's own fixed template already does everything this handler needs, with zero Custom Host Code. If you're ever unsure whether a Host Action truly needs custom logic, this is the test: do every response field either auto-match a trigger field by name, or need to be playerId? If yes, leave it blank.

06

Part 5 — Configure Relay Settings and generate#

Open Settings → Relay Settings and fill in your own coturn/rendezvous details (identical fields to every other tutorial — Relay Host, Relay Port 3478, Rendezvous URL, Credential Mode StaticSecret, TURN Username, Shared Secret). Click Save Settings.

Open Build Code, click Validate Definition, then Generate All Files. This writes to Definitions/VRDemo/Generated/:

  • Client/LoginRequest.cs, Client/PlayerJoinedEvent.cs, Client/PlayerLeftEvent.cs, Client/RequestPlayerStatusRequest.cs, Client/PlayerStatusUpdateEvent.cs, Client/RelayConnectionManager.cs
  • Host/HostActionRouter.cs
  • Config/RelayConfig.json

Let Unity recompile and check the Console for CS0103: The name 'VRGameState' does not exist or CS0103: The name 'VRDemoController' does not exist — if you see either, confirm Assets/PivecLabs/Examples/VRDemo/Scripts/ exists with the files from Part 7 (this tutorial ships them already, so a fresh import shouldn't hit this).

07

Part 6 — Create the eight sync rules#

Asset Name and Rule Name are two different things, set two different ways. Asset Name is the filename Unity gives the new .asset file in the Project window — right after creating it, Unity puts the name into an editable text field right there in the Project window; type the Asset Name column's value into that field before doing anything else. Rule Name is a separate, actual field inside the asset, set afterward in the Inspector — this is the name the runtime actually uses to key sync data, and it deliberately doesn't have to match the filename.

Every rule below is a SyncRuleDefinition asset, created in Assets/PivecLabs/Examples/VRDemo/ via right-click → Create → PivecLabs → NetCrafterRelay → Sync Rule.

Asset nameRule NameSync TargetSync ModeInterval
Sync_VRRootPositionVRRootPositionTransform_PositionOnChange0.05
Sync_VRRootRotationVRRootRotationTransform_RotationOnChange0.05
Sync_VRHeadPositionVRHeadPositionTransform_PositionOnChange0.05
Sync_VRHeadRotationVRHeadRotationTransform_RotationOnChange0.05
Sync_VRLHandPositionVRLHandPositionTransform_PositionOnChange0.05
Sync_VRLHandRotationVRLHandRotationTransform_RotationOnChange0.05
Sync_VRRHandPositionVRRHandPositionTransform_PositionOnChange0.05
Sync_VRRHandRotationVRRHandRotationTransform_RotationOnChange0.05

Set Target Component Type to Transform on all eight.

Create and rename one row at a time — don't create all eight, then rename them. Right-click → Create → ... → Sync Rule drops the new asset straight into an editable rename field in the Project window; typing the Asset Name column's value there immediately, before creating the next one, is what keeps every asset's default name unique. Skip this with eight rules in a row and Unity will silently append " 1", " 2" to keep filenames unique — the fix, if you already have one: select it, press F2, retype the correct name.

Why OnChange with a 0.05 interval, not Interval mode. OnChange sends the instant a tracked value actually moves, with interval acting as a maximum staleness backstop — a forced resend if nothing has changed in that long, not a fixed send cadence. A VR session already runs eight of these per remote player (double Character's six, on top of two more schema messages) — 0.05 keeps each individually well under this package's ~1200–1400 byte safe payload guidance while still reading as live tracked movement, not choppy. If bandwidth becomes a real concern with more players, lowering the hand rules' update rate (hands move faster/more erratically than a head, visually, but matter less when a player glances away) is a reasonable place to start tuning before touching the root or head rules.

08

Part 7 — Build the scene#

Same idea as NetCrafter's own SFS3 VR tutorial: take the OpenWorlds VR scene you already have working from Part 1, save it under a new name, and add NetCrafter Relay directly into that same scene. There's no separate "relay scene" to merge in — everything below happens in the one scene you're already standing in.

This package also ships VRDemoScene.unity (Assets/PivecLabs/Examples/VRDemo/), built the same way but without any VR content (OpenWorlds VR can't be imported into this authoring project — Part 0.2). It's a working reference showing what the finished result of this Part looks like — open it if you want to see the wiring before building your own — but build your own copy directly in your VR scene using the steps below, the same tool buttons (Prefab Generator, Scene Assistant) every other tutorial already uses.

7.1 Save your VR scene as your multiplayer scene

Open your OpenWorlds VR scene from Part 1 — the one with a working local player, head/hand tracking, and the three follower singletons confirmed. File → Save As, give it a new name (for example VRMultiplayerScene.unity). Work in this new scene from now on — never modify the original sample/demo scene it came from.

7.2 Add sync bindings to your player prefab's root

This isn't a new prefab you create — it's whichever existing character model OpenWorldsVRManager.Instance.player ends up pointing at (e.g. LabMan1.prefab, under OpenWorlds VR's own Example Models/Prefabs/). Select that prefab asset's root directly (double-click into Prefab Mode, or select it in the Project window). Twice: Add Component → NetCrafter → Sync Binding, then immediately drag VRRootPosition/VRRootRotation (Part 6) onto the two bindings' Rule fields before adding the next one — or just select the prefab root and run GameObject → NetCrafter Relay → Auto-Wire VR Local Player Root, which does the same thing in one click and is safe to re-run.

Leave Has Authority unchecked and Object Id at 0 on both — VRDemoController.ConfigureLocalPlayerWhenReady() (Part 7.7) calls Configure(id, authority) on every local binding the moment login succeeds. Setting these by hand risks locking in against the wrong value before Configure() ever runs — see the Character tutorial's Part 7.1 for the full mechanism.

If you add your own character models to OpenWorldsVRManager's own selection list (ListofPlayerModels — it's explicitly designed to be extended this way), each one needs this same step done on it too. It isn't automatic, and a model that's missing it won't error or crash — ConfigureLocalPlayerWhenReady() just has nothing to configure, so that player's position/rotation silently never reaches anyone else, leaving a frozen avatar on every other client's screen with no symptom visible locally. VRDemoController checks for this directly and logs a clear error naming exactly which rule (VRRootPosition and/or VRRootRotation) is missing from whatever model actually spawned, pointing back at the Auto-Wire tool above — watch the Console the first time you test a new model. The shipped models (LabMan1-4) are already wired, including two (LabMan3/LabMan4) that inherited the setup automatically by being Prefab Variants of LabMan2 — if your own custom models are built the same way (as variants of a model you've already wired), you may not need to run the tool on each one individually.

7.3 Add sync bindings to the three follower singletons

On each of HeadFollower, LHandFollower, and RHandFollower (Part 1.2) — the same scene-level singleton objects OpenWorlds VR itself drives, not copies — add two NetCrafterSyncBinding components each:

ObjectRule 1Rule 2
HeadFollowerVRHeadPositionVRHeadRotation
LHandFollowerVRLHandPositionVRLHandRotation
RHandFollowerVRRHandPositionVRRHandRotation

Leave all six unchecked, same reasoning as Part 7.2 — ConfigureLocalPlayerWhenReady() finds all three followers (polling for up to 3 seconds, since they're activated asynchronously after player assignment — see Part 1.2) and configures their bindings too.

7.4 Build the remote avatar prefab

Step 1 — Duplicate, unpack, and check. Duplicate your player prefab (the one from Part 7.2), rename the duplicate RemoteVRCharacterPrefab. If the original wasn't already unpacked, right-click the duplicate → Prefab → Unpack Completely now, before touching any components — a duplicated prefab instance can still be linked to the same source as the original, and editing one can silently affect the other, or saving the duplicate can produce a Prefab Variant instead of an independent prefab (same confirmed trap as every other tutorial's remote-prefab step).

Step 2 — Remove local-only components. Remove whatever OpenWorlds VR component(s) drive local input/tracking directly from the XR rig (your own local-only movement/tracking script) — a remote avatar is driven entirely by incoming network data, never by this machine's own XR devices. Leave the Animator in place, and confirm its Controller field is still assigned (the same controller your local player model uses, e.g. OpenWorldsVR_Animator.controller) — an Animator with no Controller assigned plays no animations and holds no pose at all, which looks exactly like a deformed/broken remote avatar even though every sync value arriving over the network is correct. Duplicating the prefab in Step 1 normally carries this reference over automatically, but it's easy to lose if the remote prefab was built some other way (a fresh prefab, a different source model, or the Animator component itself got removed and re-added) — always worth a direct look at the Inspector rather than assuming.

Step 3 — Add RemoteVRCharacterController, VRColorManager, PlayerNameDisplay. Assets/PivecLabs/Examples/VRDemo/Scripts/RemoteVRCharacterController.cs ships with the package:

Show RemoteVRCharacterController.csships with the package — nothing to type
C#
using System.Reflection;
using UnityEngine;

namespace PivecLabs.NetCrafterRelay.Examples.VRDemo
{
    // Sets up IK and applies animation state for a remote VR player's avatar. Root position/
    // rotation and head/hand pose are NOT driven by this script at all -- they're driven
    // directly by NetCrafterSyncBinding components (Transform_Position/Transform_Rotation) on
    // this GameObject (root) and on the headTarget/lHandTarget/rHandTarget children below,
    // exactly like every other remote object in every other Relay tutorial. This is a
    // deliberate simplification versus the ported SFS3 tutorial, which had to manually lerp the
    // root and reconstruct head/hand pose from player-root-relative floats every frame in
    // Update() -- Relay's sync system already applies a world-space position/rotation directly
    // to whatever GameObject the binding sits on, so a plain child target under the remote root
    // ends up in the exact right place with zero extra math, and the established Relay
    // convention (confirmed in the Character/Racing tutorials) is to apply incoming sync values
    // directly, with no interpolation layer.
    //
    // headTarget/lHandTarget/rHandTarget/bodyTarget must already exist as children of this
    // GameObject in the PREFAB, each (except bodyTarget) carrying its own two NetCrafterSyncBinding
    // components (Transform_Position + Transform_Rotation, wired to the matching VRHeadPosition/
    // VRHeadRotation/etc. sync rule) -- see Tutorial_VR.html Part B3. They are NOT created at
    // runtime: NetCrafterSyncBinding's Rule field is Inspector-only with no public setter (by
    // design, matching every other sync binding in every other Relay tutorial), so there is no
    // way to wire a freshly-created GameObject to the correct rule from code.
    //
    // PlayerIKSolver ships compiled in OpenWorldsVR.dll with no source in this project, so it
    // cannot be referenced by type here -- it is located and driven entirely by reflection. The
    // field/method names below were confirmed by reflecting OpenWorldsVR.dll v1.3.1 directly
    // (not guessed) -- see Tutorial_VR.html Part A3 for how, and re-verify if a future OpenWorldsVR
    // version renames anything and this stops working.
    public class RemoteVRCharacterController : MonoBehaviour
    {
        [Header("IK targets — pre-built children, see Tutorial_VR.html Part B3")]
        public Transform headTarget;
        public Transform lHandTarget;
        public Transform rHandTarget;
        [Tooltip("Local offset (from the character root) for the body/spine IK target. " +
                 "Rotation always matches the root's own facing exactly (zero local rotation) " +
                 "-- only position is tunable. Raise Y if the spine looks twisted/collapsed.")]
        public Vector3 bodyTargetLocalOffset = Vector3.zero;

        [Tooltip("Diagnostic toggle — skips adding PlayerIKSolver entirely when false. Useful " +
                 "for isolating whether PlayerIKSolver is interfering with root rotation/" +
                 "position: set false and retest before trusting any conclusion drawn while a " +
                 "different bug (e.g. a missing Animator Controller) was also present.")]
        public bool enableIK = true;

        [Header("Grounded check — derived locally, not from the network (see class comment)")]
        public LayerMask groundLayers = ~0;
        public float groundCheckRadius = 0.3f;
        public float groundCheckDistance = 0.3f;

        [Header("Movement animation — derived locally, not from the network (see class comment)")]
        [Tooltip("Matches OpenWorldsVRManager's own walkSpeed/runningSpeed x SetMoveSpeed defaults " +
                 "(0.5 and 1.0, times a default SetMoveSpeed of 3 = 1.5 and 3.0 units/sec) -- the " +
                 "threshold here sits roughly halfway between them. Adjust if your project tunes " +
                 "SetMoveSpeed differently.")]
        public float idleSpeedThreshold = 0.1f;
        public float runSpeedThreshold = 2.25f;

        private Animator _animator;
        private Vector3 _lastTrackedPosition;
        private float _lastTrackedSampleTime;
        private bool _hasLastTrackedPosition;

        // PlayerIKSolver, reached only via reflection -- see class comment above.
        private Component _ikSolver;
        private Transform _bodyTarget;
        private bool? _lastAppliedDesktopMode;

        private void Awake()
        {
            _animator = GetComponent<Animator>();

            // Gives other players' CharacterControllers something to collide against.
            if (GetComponent<CapsuleCollider>() == null)
            {
                var capsule = gameObject.AddComponent<CapsuleCollider>();
                capsule.center = new Vector3(0f, 1f, 0f);
                capsule.radius = 0.3f;
                capsule.height = 2f;
            }

            // Silences "SendMessage: No receiver found" for the baked footstep/landing
            // animation events -- see RemoteAnimationEventReceiver.cs.
            if (GetComponent<RemoteAnimationEventReceiver>() == null)
                gameObject.AddComponent<RemoteAnimationEventReceiver>();

            InitializeRemoteIKSolver();
        }

        private void InitializeRemoteIKSolver()
        {
            if (!enableIK)
            {
                Debug.Log("[VRDemo Remote] enableIK is false — skipping PlayerIKSolver entirely.");
                return;
            }

            if (headTarget == null || lHandTarget == null || rHandTarget == null)
            {
                Debug.LogError("[VRDemo] RemoteVRCharacterController.headTarget/lHandTarget/rHandTarget " +
                    "must be wired in the Inspector (see Tutorial_VR.html Part B3) — skipping PlayerIKSolver.");
                return;
            }

            var ikType = System.Type.GetType("OpenWorldsVR.PlayerIKSolver, OpenWorldsVR");
            if (ikType == null)
            {
                Debug.LogWarning("[VRDemo] PlayerIKSolver type not found. Is OpenWorlds VR for " +
                    "Third Person v1.3.1+ imported, and NETCRAFTER_VR_EXAMPLE added to Scripting " +
                    "Define Symbols?");
                return;
            }

            _ikSolver = gameObject.AddComponent(ikType);

            // Fix for "upper body twisted relative to lower body": with IsBodyActive false and
            // no remoteBodyTarget, the solver's spine has nothing tying it to the root's actual
            // facing. This target needs no per-frame updates: it's a plain child at a fixed
            // local offset with zero local rotation, so its world rotation always equals the
            // root's transform.rotation exactly, for free, via normal Unity parenting -- and the
            // root's rotation is itself kept correct by its own NetCrafterSyncBinding. Created at
            // runtime (not pre-built, unlike the IK targets above) because it carries no sync
            // binding of its own -- nothing on the wire needs to reach it.
            var bodyGo = new GameObject("RemoteBodyTarget");
            bodyGo.transform.SetParent(transform, false);
            bodyGo.transform.localPosition = bodyTargetLocalOffset;
            _bodyTarget = bodyGo.transform;

            SetField("remoteHeadTarget",  headTarget.gameObject);
            SetField("remoteLHandTarget", lHandTarget.gameObject);
            SetField("remoteRHandTarget", rHandTarget.gameObject);
            SetField("remoteBodyTarget",  _bodyTarget.gameObject);
            SetField("playerAnimator", _animator);

            SetField("remotePlayer",  true);
            // Every player goes through Login/Lobby with mouse+keyboard before they can ever put
            // a headset on, so "desktop mode" is the one state every remote avatar is GUARANTEED
            // to start in -- spawning with head/hand IK already active assumed the opposite, and
            // left a freshly-spawned avatar reaching for stale/default head/hand target data
            // (deformed-looking) for however long it took the first real PlayerStatusUpdate to
            // arrive and correct it via ApplyDesktopModeIfChanged. Starting IK off instead means
            // the only visible transition is desktop -> VR, if and when that sender actually puts
            // a headset on -- never VR -> desktop on every single spawn regardless of reality.
            SetField("IsHeadActive",  false);
            SetField("IsLHandActive", false);
            SetField("IsRHandActive", false);
            // Permanently false: there is no body/hip pose on the wire in either mode, unlike
            // head/hands which carry real tracked data whenever the sender isn't in desktop mode.
            SetField("IsBodyActive",  false);
            // Matches the false values just set above -- so ApplyDesktopModeIfChanged only acts
            // (and only logs/toggles) the first time a real status update disagrees with this
            // assumed starting point, i.e. the first time the sender is actually in VR mode.
            _lastAppliedDesktopMode = true;

            InvokeMethod("Configure");

            // Confirmed live: IsHeadActive/IsLHandActive/IsRHandActive/IsBodyActive all false
            // does NOT fully stop PlayerIKSolver from bending the body over -- only actually
            // disabling the component itself does (confirmed by manually unchecking it in the
            // Inspector at runtime). Whatever the solver does internally with those flags, it's
            // not "stop touching posture entirely" the way the names suggest. PlayerIKSolver is a
            // MonoBehaviour (a Behaviour), so its own `enabled` is reachable directly -- no
            // reflection needed for this part. Starts disabled to match the desktop-mode default
            // above; ApplyDesktopModeIfChanged flips it on exactly when (and only when) the
            // sender is confirmed to actually be in VR mode.
            if (_ikSolver is Behaviour ikBehaviour)
                ikBehaviour.enabled = false;
        }

        private void SetField(string fieldName, object value)
        {
            if (_ikSolver == null) return;
            var field = _ikSolver.GetType().GetField(fieldName, BindingFlags.Public | BindingFlags.Instance);
            if (field != null)
                field.SetValue(_ikSolver, value);
            else
                Debug.LogWarning($"[VRDemo] PlayerIKSolver has no public field '{fieldName}'. " +
                    "OpenWorldsVR may have changed its API — see Tutorial_VR.html Part A3.");
        }

        private void InvokeMethod(string methodName)
        {
            if (_ikSolver == null) return;
            var method = _ikSolver.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance);
            method?.Invoke(_ikSolver, null);
        }

        // Called whenever a PlayerStatusUpdate for this player arrives (VRDemoController.
        // OnPlayerStatusUpdateReceived) -- edge-triggered on the SENDER's side already (see
        // VRDemoController.PollStatusChanges), so every call here really is a change, not a
        // per-frame poll.
        //
        // Confirmed live: "grounded" AND "animState" used to come from here (the sender's own
        // values, both carried over the same reliable PlayerStatusUpdate/RequestPlayerStatus
        // channel). That channel can be delayed or dropped under real-world network conditions
        // (confirmed live across an extended investigation this session -- weak Wi-Fi/an older
        // machine, not a code bug, but still a real condition this package has to tolerate) --
        // and unlike isDesktopMode (where a stale value is only briefly the wrong IK mode), a
        // stale grounded/animState value is immediately and visibly wrong: the avatar hovers, or
        // freezes in a single pose (confirmed live: Idle, its spawn default) while sliding along
        // to the correct position every tick regardless, since that comes from the separate,
        // much more frequent, already-working unreliable sync. Both are now derived locally every
        // frame in Update()/ApplyLocalMovementAnimState from the root position this avatar's own
        // Transform_Position sync binding already keeps current, the same way
        // OpenWorldsVRManager.GroundedCheck()/AnimatePlayer() derive them for the local player, so
        // neither can go stale regardless of how this one reliable message is delivered.
        //
        // isDesktopMode deliberately stays network-driven, unlike the two above -- confirmed live
        // that inferring it locally from head/hand target position freshness doesn't work in
        // either direction: a desktop sender's head/hand stand-in position still moves whenever
        // they walk (not real head tracking, but not static either), so "position changing ->
        // assume VR" produced a VR-distorted pose on every desktop player the instant they moved;
        // and a real VR player standing still can have their actual tracked head position read as
        // bit-for-bit static for well over a second (many XR runtimes filter out exactly this kind
        // of sub-threshold jitter), so "position static -> assume desktop" dropped a genuinely-VR
        // player's arm IK the moment they stopped walking. There's no local signal that
        // disambiguates "stationary but still in VR" from "headset came off" -- only the sender
        // actually knows that. The real gap this was chasing (the headset-off transition getting
        // lost entirely while the sender stays otherwise stationary, so nothing else ever
        // re-sends the correct value) is fixed properly in VRDemoController.PollStatusChanges's
        // own periodic backstop resend instead.
        public void ApplyStatus(int animState, bool grounded, bool isDesktopMode)
        {
            ApplyDesktopModeIfChanged(isDesktopMode);
        }

        private void Update()
        {
            if (!IsAnimatorReady(_animator)) return;

            Ray ray = new Ray(transform.position + Vector3.up * 2f * groundCheckRadius, Vector3.down);
            bool grounded = Physics.SphereCast(ray, groundCheckRadius, groundCheckDistance + groundCheckRadius,
                groundLayers, QueryTriggerInteraction.Ignore);
            _animator.SetBool("Grounded", grounded);

            ApplyLocalMovementAnimState(grounded);
        }

        // Doesn't attempt to replicate the sender's exact "JumpLand" landing flourish (a
        // transient one-off cosmetic animation, not something reliably detectable from discrete
        // position snapshots alone) -- falling straight back to grounded walk/idle on landing is
        // a far smaller gap than never animating while walking at all.
        //
        // Confirmed live: this used to compute velocity against Time.deltaTime (one frame, ~16ms)
        // every single frame -- but the synced position only actually CHANGES once per incoming
        // sync tick (~every 50-100ms via the VRRootPosition rule's OnChange/backstop), not every
        // frame. On the one frame a new position lands, a whole sync-interval's worth of movement
        // was being divided by a single frame's time, overestimating speed several times over
        // (reliably reading as Run regardless of the sender's real speed) -- and on every frame in
        // between, position hadn't moved at all since the LAST frame, computing zero velocity
        // (Idle). The net effect was flickering between Idle and Run rather than a stable Walk,
        // which read as "stuck"/not moving.
        //
        // Confirmed live (second bug, from the first fix): holding the last applied state steady
        // whenever position hasn't changed since the last sample also means Idle itself -- which
        // IS "position stopped changing" -- could never get re-derived once the sender actually
        // stopped moving. The Animator just kept playing whatever Walk/Run state was last applied,
        // forever, since the exact condition that defines "stopped" is the same one that made this
        // method skip re-evaluating at all. Fixed by tracking how long it's been since the last
        // REAL position change separately from the walk/run derivation itself -- once that's long
        // enough that a stationary sender's own OnChange backstop would have resent by now anyway
        // (so this isn't just "waiting for the next tick"), force Idle/InAir every frame until
        // real movement resumes, instead of only ever reacting to a position that's still changing.
        private const float PositionChangeEpsilonSqr = 0.0001f * 0.0001f;
        private const float IdleConfirmSeconds = 0.25f; // comfortably longer than the 0.1s sync backstop

        private void ApplyLocalMovementAnimState(bool grounded)
        {
            Vector3 currentPosition = transform.position;
            float now = Time.time;

            if (!_hasLastTrackedPosition)
            {
                _lastTrackedPosition = currentPosition;
                _lastTrackedSampleTime = now;
                _hasLastTrackedPosition = true;
                return;
            }

            bool positionChanged = (currentPosition - _lastTrackedPosition).sqrMagnitude >= PositionChangeEpsilonSqr;

            if (!positionChanged)
            {
                if (now - _lastTrackedSampleTime >= IdleConfirmSeconds)
                    ApplyAnimState(_animator, grounded ? 0 : 9);
                return; // either still within the "could just be waiting for the next tick"
                        // window, or already confirmed Idle/InAir above -- nothing new to derive
            }

            float elapsed = now - _lastTrackedSampleTime;
            Vector3 worldVelocity = elapsed > 0f
                ? (currentPosition - _lastTrackedPosition) / elapsed
                : Vector3.zero;
            _lastTrackedPosition = currentPosition;
            _lastTrackedSampleTime = now;

            Vector3 localVelocity = transform.InverseTransformDirection(worldVelocity);
            localVelocity.y = 0f; // vertical movement isn't a walk/run direction

            int animState;
            if (!grounded)
            {
                animState = 9; // InAir
            }
            else if (localVelocity.magnitude < idleSpeedThreshold)
            {
                animState = 0; // Idle
            }
            else
            {
                bool running = localVelocity.magnitude > runSpeedThreshold;
                // Strafe wins over forward/back, mirroring OpenWorldsVRManager.AnimatePlayer()'s
                // own priority for the exact same ambiguous-direction case.
                if (Mathf.Abs(localVelocity.x) >= Mathf.Abs(localVelocity.z))
                    animState = localVelocity.x < 0f ? (running ? 7 : 3) : (running ? 8 : 4);
                else
                    animState = localVelocity.z < 0f ? (running ? 6 : 2) : (running ? 5 : 1);
            }

            ApplyAnimState(_animator, animState);
        }

        // Disables head/hand IK rather than letting the solver resolve toward whatever stale
        // tracked pose the last real update left the targets at -- mirrors
        // OpenWorldsVRManager.PlayerIKOff() for the local player. IsBodyActive is untouched
        // (stays permanently false regardless of desktop mode -- see InitializeRemoteIKSolver).
        //
        // Confirmed live: the Is*Active fields alone don't stop the solver from bending the body
        // over in desktop mode -- only disabling the component itself does (see
        // InitializeRemoteIKSolver's comment). So the component's own `enabled` is the real
        // on/off switch; the Is*Active fields below are kept so the solver's internal state is
        // already correct for whenever it next gets re-enabled in VR mode, not because they do
        // anything on their own while desktop mode is active.
        private void ApplyDesktopModeIfChanged(bool isDesktopMode)
        {
            if (_lastAppliedDesktopMode.HasValue && _lastAppliedDesktopMode.Value == isDesktopMode)
                return;

            if (_ikSolver is Behaviour ikBehaviour)
                ikBehaviour.enabled = !isDesktopMode;

            bool active = !isDesktopMode;
            SetField("IsHeadActive",  active);
            SetField("IsLHandActive", active);
            SetField("IsRHandActive", active);

            _lastAppliedDesktopMode = isDesktopMode;
        }

        private static bool IsAnimatorReady(Animator anim) =>
            anim != null && anim.runtimeAnimatorController != null && anim.isActiveAndEnabled;

        // Inverse of VRDemoController.GetAnimState() on the sending side -- maps the wire int
        // back onto OpenWorldsVR_Animator.controller's per-direction bools. Clears all of them
        // first since exactly one should be active.
        private static void ApplyAnimState(Animator anim, int animState)
        {
            anim.SetBool("Idle", false);
            anim.SetBool("WalkForward", false);
            anim.SetBool("WalkBackward", false);
            anim.SetBool("WalkLeft", false);
            anim.SetBool("WalkRight", false);
            anim.SetBool("RunForward", false);
            anim.SetBool("RunBackward", false);
            anim.SetBool("RunLeft", false);
            anim.SetBool("RunRight", false);
            anim.SetBool("InAir", false);
            anim.SetBool("JumpLand", false);

            switch (animState)
            {
                case 1:  anim.SetBool("WalkForward", true);  break;
                case 2:  anim.SetBool("WalkBackward", true); break;
                case 3:  anim.SetBool("WalkLeft", true);     break;
                case 4:  anim.SetBool("WalkRight", true);    break;
                case 5:  anim.SetBool("RunForward", true);   break;
                case 6:  anim.SetBool("RunBackward", true);  break;
                case 7:  anim.SetBool("RunLeft", true);      break;
                case 8:  anim.SetBool("RunRight", true);     break;
                case 9:  anim.SetBool("InAir", true);        break;
                case 10: anim.SetBool("JumpLand", true);     break;
                default: anim.SetBool("Idle", true);         break;
            }
        }
    }
}

On RemoteVRCharacterPrefab's root: Add Component → Remote VR Character Controller, VR Color Manager, Player Name Display.

Step 4 — Build the three IK target children. Under the prefab root, create three empty children: HeadTarget, LHandTarget, RHandTarget (these exact names — the auto-wire tool below, and RemoteVRCharacterController itself, both depend on them). Then either wire the rest by hand, or let the editor do it: select the prefab root and use GameObject → NetCrafter Relay → Auto-Wire VR Remote Character — it adds and assigns all 8 NetCrafterSyncBinding components (position + rotation on the root, plus each of the three children) and wires RemoteVRCharacterController's Head Target/L Hand Target/R Hand Target fields in one click. Safe to re-run — it reuses any binding already pointed at the right rule (or left unassigned) instead of adding duplicates, so running it again after manually tweaking something won't undo your work. By hand: on each child, add the matching two NetCrafterSyncBinding components — the same six rules as Part 7.3 (VRHeadPosition/VRHeadRotation on HeadTarget, and so on), left unchecked — then drag the three Transforms into RemoteVRCharacterController's fields yourself.

RemoteVRCharacterController creates a fourth target, RemoteBodyTarget, itself at runtime — it carries no sync binding (nothing on the wire targets the body/hips), it's just a fixed local offset so the IK solver's spine always matches the root's own synced rotation, for free, via ordinary Unity parenting. Nothing to build for this one.

Step 5 — Name tag. Add a world-space NameCanvas child (not on the prefab root — see Common Mistakes) with a NameText TMP text child. Wire NameCanvas/NameText into PlayerNameDisplay's fields.

Step 6 — Save and remove from the Hierarchy. Before saving, reset the prefab root's own Transform to Position (0, 0, 0) and Rotation (0, 0, 0) (right-click the Transform component → Reset) — a duplicated prefab (Step 1) commonly keeps whatever position/rotation its source happened to be at in the scene, and a remote instance spawned at that leftover offset can end up far enough away to never be seen at all, with no error to explain why, until the first VRRootPosition sync update happens to arrive and move it. Drag RemoteVRCharacterPrefab into Assets/PivecLabs/Examples/VRDemo/Prefabs/ (create the Prefabs folder first — the package doesn't include it, because this prefab is built from OpenWorldsVR, which you import yourself), then delete it from the Hierarchy.

7.5 Build the UI

Directly in your saved VR scene (Part 7.1):

  1. Canvas — name it UICanvas. Set Render Mode to World Space (not Screen Space Overlay — Part 0.1), position it a short distance in front of where your player starts (for example (0, 1.6, 1.5)), and scale it down for a comfortable reading size (world-space canvases are sized in pixels — a few hundred pixels wide at a scale around 0.0015 on all three axes reads as a normal-sized panel at arm's length; adjust to taste once you can see it in headset).
  2. LoginPanel: TMP Text (Title, "VR Demo"), TMP Input Field (DisplayNameInput, placeholder "Enter your name..."), TMP Button (ContinueButton, "Continue").
  3. LobbyPanel (unchecked by default): TMP Button (HostButton, "Host Game"), TMP Button (JoinButton, "Join Game"), TMP Input Field (JoinCodeInput, placeholder "Join code..."), TMP Text (JoinCodeDisplay, blank), TMP Text (StatusText, blank).
  4. GameplayPanel (unchecked by default): TMP Text (PlayerListText, blank).

Check for an EventSystem before adding one. OpenWorlds VR's own sample scene commonly already includes one — adding a second causes duplicate-input warnings and unpredictable UI focus. If you do need to add one, make sure it uses Input System UI Input Module, not the legacy Standalone Input Module — this project's Active Input Handling is set to Input System Package (Prerequisites), and the legacy module throws an exception at runtime under that setting.

7.6 Create the RelayConnectionManager prefab and add the relay/event GameObjects

Open Scenes → Prefab Generator, confirm VRDemo is selected, click Create RelayConnectionManager Prefab (writes to Definitions/VRDemo/Prefabs/, a sibling of Generated/ — never touched by code regeneration; this tutorial already ships this prefab if you're using the shipped schema, so this only matters if you rebuilt the schema from scratch in Part 2).

Open Scenes → Scene Assistant, confirm VRDemo is still selected, confirm Add Event Dispatcher is checked, click Add to Existing Scene. This adds, directly into your VR scene:

  • RelayConnectionManager — an instance of the prefab you just created, added already disabled.
  • HostActionRouter — VRDemo's generated host-side logic dispatcher.
  • NetCrafterEventDispatcher.
  • NetCrafterSyncManager — added automatically because VRDemo has SyncRuleDefinition assets (Part 6).

Why the RelayConnectionManager GameObject starts disabled. Its Start() calls Connect() unconditionally, which defaults to hosting a new session when no join code is pending — active from the instant the scene loads, it would start hosting before Login has even been looked at. VRDemoController.Awake() also forces it inactive defensively, the same belt-and-suspenders pattern every tutorial in this package uses.

Then: Settings → Scene Events → Add Router to Scene — creates a SceneEventRouter GameObject listing PlayerJoined, PlayerLeft, and PlayerStatusUpdate, each with an empty On Received slot (wired in 7.7).

7.7 Attach and wire VRDemoController, and enable the define

Create an empty GameObject named NetworkManager, drag the script onto it.

  1. On NetworkManager, drag RemoteVRCharacterPrefab.prefab (Part 7.4) into VRDemoController's Remote Character Prefab field, and wire every other field: Relay Connection Manager Object → the RelayConnectionManager GameObject; Login Panel/Display Name Input, Lobby Panel/Join Code Input/Join Code Display/Status Text, Gameplay Panel/Player List Text → the matching objects from Part 7.5.
  2. Wire the buttons and events: ContinueButton → On Click() → VRDemoController.OnLoginClicked(); HostButton → VRDemoController.OnHostClicked(); JoinButton → VRDemoController.OnJoinClicked(); SceneEventRouter's PlayerJoined binding → On Received → VRDemoController.OnPlayerJoinedReceived(); PlayerLeft binding → VRDemoController.OnPlayerLeftBroadcastReceived(); PlayerStatusUpdate binding → VRDemoController.OnPlayerStatusUpdateReceived().
  3. Edit → Project Settings → Player → Scripting Define Symbols (for your active platform) → add NETCRAFTER_VR_EXAMPLE, then let Unity recompile.
Show VRDemoController.csships with the package — nothing to type
C#
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using TMPro;
using PivecLabs.Generated.VR;
using PivecLabs.NetCrafterRelay;

#if NETCRAFTER_VR_EXAMPLE
using PivecLabs.OpenWorldsVR;
#endif

namespace PivecLabs.NetCrafterRelay.Examples.VRDemo
{

// Reference implementation backing the "NetCrafter Relay — Multiplayer VR" tutorial.
// Host-relay-only, same as every other schema: joiners never talk to each other directly, only
// through the host. Combines what the ported SFS3 tutorial split into VRNetworkManager +
// VRUIManager into one controller, matching the single-controller convention every other Relay
// tutorial already uses (ChatDemoController, CoopDemoController, CharacterDemoController,
// RacingDemoController).
//
// NETCRAFTER_VR_EXAMPLE guards every line that references an actual OpenWorldsVR type
// (OpenWorldsVRManager, HeadFollower, LHandFollower, RHandFollower) -- NOT the whole file. Those
// types only exist once you've imported OpenWorlds VR for Third Person (Asset Store, sold
// separately -- see the tutorial doc's Prerequisites) into YOUR project; this package can't
// bundle or assume it. The class itself, its fields, and the networking/UI logic around it
// compile and work unconditionally, because generated HostActionRouter.cs calls
// VRDemoController.Instance?.HostRegisterPlayerLocally(...) directly (see HandleLogin's Custom
// Host Code) -- that reference must resolve whether or not OpenWorldsVR is present, which an
// outer "#if guards the whole file" wrapper (the approach NetCrafter's own SFS3 VR tutorial
// uses) would break. Add NETCRAFTER_VR_EXAMPLE to Scripting Define Symbols once OpenWorldsVR is
// imported -- see the tutorial doc's Part A1.
public class VRDemoController : MonoBehaviour
{
    // Referenced by HandleLogin's Custom Host Code -- the host process needs a way to call back
    // into its own running scene, since BroadcastToAll never loops back to the sender's own
    // incoming-message pipeline.
    public static VRDemoController Instance { get; private set; }
    // Fast Enter Play Mode (Reload Domain off) keeps static values between Play sessions: reset them on entering Play mode.
    [UnityEngine.RuntimeInitializeOnLoadMethod(UnityEngine.RuntimeInitializeLoadType.SubsystemRegistration)]
    private static void ResetStaticsForPlayMode() { Instance = null; }

    [Header("Relay (starts inactive -- see tutorial doc for why)")]
    public GameObject relayConnectionManagerObject;

    [Header("Login panel")]
    public GameObject loginPanel;
    public TMP_InputField displayNameInput;

    [Header("Lobby panel")]
    public GameObject lobbyPanel;
    public TMP_InputField joinCodeInput;
    public TMP_Text joinCodeDisplay;
    public TMP_Text statusText;

    [Header("Gameplay panel")]
    public GameObject gameplayPanel;
    public TMP_Text playerListText;

    [Header("VR")]
    public GameObject remoteCharacterPrefab;

    private RelayConnectionManager relay;
    private string displayName = "Player";
    private NetCrafterSyncBinding[] _localRootBindings;
#if NETCRAFTER_VR_EXAMPLE
    // Cached once in ConfigureLocalPlayerWhenReady -- see UpdateHeadsetOffHeadFlag/
    // SetFollowersEnabled for why these need to be reachable outside that coroutine.
    private HeadFollower _headFollower;
    private LHandFollower _lHandFollower;
    private RHandFollower _rHandFollower;
#endif
    private readonly Dictionary<int, GameObject> _remoteCharacters = new();
    private readonly Dictionary<int, string> _remotePlayerNames = new();

#if NETCRAFTER_VR_EXAMPLE
    // Only read/written by the VR status loop below, which is itself VR-only --
    // declared conditionally so non-VR builds don't warn (CS0414).
    private int _lastSentAnimState = -1;
    private bool _lastSentGrounded;
    private bool _lastSentIsDesktopMode;
    private bool _hasSentStatusOnce;
    private float _lastStatusSendTime;
#endif

    private const float StatusPollInterval = 0.1f;
    private const float HeadsetPollInterval = 0.5f;
    // Confirmed live: a single edge-triggered PlayerStatusUpdate/RequestPlayerStatus carrying an
    // isDesktopMode change (e.g. the sender's headset just came off) can be delayed or dropped by
    // the reliable channel under real-world network conditions (see RemoteVRCharacterController's
    // ApplyStatus comment) -- and if the sender stays otherwise stationary afterward (no further
    // animState/grounded change to piggyback a fresh send on), nothing ever resends the correct
    // value again, leaving the remote avatar's arm IK stuck reaching for head/hand targets that
    // have themselves gone static. Same OnChange+backstop pattern this project's own sync rules
    // already use for exactly this reason (SyncRuleDefinition) -- resending the current status
    // periodically regardless of whether anything changed means a dropped edge-triggered send
    // gets a fresh chance within one backstop interval, not "forever" (or until some unrelated
    // field happens to change too). Far more frequent than MaintainKeepAlive's 120s permission
    // refresh -- this field changes rarely, but needs to self-heal fast when it does.
    private const float StatusBackstopInterval = 1.5f;

    private void Awake()
    {
        Instance = this;
        VRGameState.Reset();

        relay = relayConnectionManagerObject.GetComponent<RelayConnectionManager>();
        relayConnectionManagerObject.SetActive(false);

        ShowLogin();
    }

    private void OnDestroy()
    {
        if (Instance == this)
            Instance = null;
    }

    private void Start()
    {
        NetCrafterEventDispatcher.Instance.Subscribe("RelayHosting", OnRelayHosting);
        NetCrafterEventDispatcher.Instance.Subscribe("ConnectionLost", OnConnectionLost);
        NetCrafterEventDispatcher.Instance.Subscribe("RelayStatus", OnRelayStatus);

        // The physical keyboard can't be typed on with a headset worn and tracking normally --
        // there's no mouse pointer to click the field into focus. Same technique
        // VRNetworkManager/VRUIManager used in the SFS3 tutorial: poll isHeadsetOffHead (or a
        // direct XR head-node check) and toggle the input fields' interactable state live.
        StartCoroutine(MonitorHeadsetState());
    }

    // The join code stays visible during play (top-right), for host and joiners alike, so
    // anyone can read it out to a friend without going back to the lobby.
    private string _currentJoinCode;
    private TMP_Text _hudJoinCode;

    private void ShowHudJoinCode(bool show)
    {
        if (!show || string.IsNullOrEmpty(_currentJoinCode) || joinCodeDisplay == null)
        {
            if (_hudJoinCode != null) _hudJoinCode.gameObject.SetActive(false);
            return;
        }
        if (_hudJoinCode == null)
        {
            var canvas = joinCodeDisplay.canvas != null ? joinCodeDisplay.canvas.rootCanvas : null;
            if (canvas == null) return;
            var go = Instantiate(joinCodeDisplay.gameObject, canvas.transform, false);
            go.name = "HudJoinCode";
            _hudJoinCode = go.GetComponent<TMP_Text>();
            var rt = (RectTransform)go.transform;
            rt.anchorMin = rt.anchorMax = rt.pivot = new Vector2(1f, 1f);
            rt.anchoredPosition = new Vector2(-24f, -70f);
            rt.sizeDelta = new Vector2(420f, 44f);
            _hudJoinCode.alignment = TextAlignmentOptions.TopRight;
            _hudJoinCode.raycastTarget = false;
            if (canvas.renderMode != RenderMode.WorldSpace)   // world-space (VR) panels keep the lobby text's size
            {
                _hudJoinCode.enableAutoSizing = false;
                _hudJoinCode.fontSize = 26f;
            }
        }
        _hudJoinCode.text = "Join code: <b>" + _currentJoinCode + "</b>";
        _hudJoinCode.gameObject.SetActive(true);
    }

    private void ShowLogin() { loginPanel.SetActive(true); lobbyPanel.SetActive(false); gameplayPanel.SetActive(false); ShowHudJoinCode(false); }
    private void ShowLobby() { loginPanel.SetActive(false); lobbyPanel.SetActive(true); gameplayPanel.SetActive(false); ShowHudJoinCode(false); }
    // Confirmed live: entering Gameplay does NOT reliably hand the cursor back to
    // OpenWorldsVRManager Locked, despite the Update() comment above assuming it would.
    // OpenWorldsVRManager only ever re-locks the cursor itself via hideCharacterPanel()'s
    // FadeOut() -- and that call is guarded by `if (characterPanelshowing)`, which is false
    // on this project's LoadPrefab(0) bypass path (see LoadPrefabCoroutine), since
    // showCharacterPanel() is what sets characterPanelshowing=true and we never call it.
    // So once Login/Lobby's per-frame "force None" loop above stops running (gameplayPanel
    // active), lockState just stays at the None it was left in -- nothing else ever sets it
    // back to Locked -- and desktop mouse-look (OpenWorldsVRManager.MouseInput(), which only
    // applies look input when Cursor.lockState == Locked) silently never engages, even though
    // WASD movement (gated only on isHeadsetOffHead, not on cursor state) works fine. Restore
    // it explicitly on the one-time Login/Lobby -> Gameplay transition; harmless when a headset
    // is actually worn too, since OpenWorldsVRManager's own Awake() sets the same state at
    // startup for the same reason.
    private void ShowGameplay()
    {
        ShowHudJoinCode(true);
        loginPanel.SetActive(false);
        lobbyPanel.SetActive(false);
        gameplayPanel.SetActive(true);
        ClearEventSystemSelection();
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    // Confirmed live: merging this tutorial's Login/Lobby UI into OpenWorlds VR's own sample
    // scene (desktop/PCtoVR fallback testing, no headset worn) exposed a real cursor conflict
    // that has nothing to do with Login/Lobby/Gameplay at all -- OpenWorldsVRManager's own
    // FadeIn()/FadeOut() (driving its character-selection panel's fade, which still runs on its
    // own 0.5s timers even though SendLoginWhenConnected's LoadPrefab(0) call bypasses ever
    // showing that panel) unlock/lock Cursor.lockState on a schedule completely independent of
    // which of OUR panels is active. Same fix as the Character tutorial's own cursor-lock
    // conflict with StarterAssetsInputs: re-assert the cursor every frame instead of relying on
    // a one-time call, so OpenWorldsVRManager's own fade timers can never leave it stuck hidden
    // behind Login or Lobby. Left alone during Gameplay -- that's OpenWorldsVRManager's own
    // desktop-mouselook cursor to manage at that point, not this controller's concern.
    private void Update()
    {
        // Confirmed live: OpenWorldsVRManager's FadeIn()/FadeOut() only ever set
        // Cursor.lockState (never Cursor.visible directly) -- CursorLockMode.Locked hides the
        // cursor as a side effect regardless of Cursor.visible's own value, so lockState is the
        // thing that actually needs checking here, not visible (which this project's version of
        // OpenWorlds VR never touches, and so is never a reliable signal of the real problem).
        if (!gameplayPanel.activeSelf && Cursor.lockState != CursorLockMode.None)
        {
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;
        }
    }

    // playerNameInput/joinCodeInput are commonly still the EventSystem's selected object after
    // the player clicks a button to move on -- deactivating the panel doesn't clear that
    // selection on its own, and with a VR pointer/laser interacting with world-space UI this can
    // leave a stale input field intercepting events. Same pattern as the Character tutorial's
    // cursor handling, adapted for VR.
    private static void ClearEventSystemSelection()
    {
        if (EventSystem.current != null)
            EventSystem.current.SetSelectedGameObject(null);
    }

    private IEnumerator MonitorHeadsetState()
    {
        var wait = new WaitForSeconds(HeadsetPollInterval);
        while (true)
        {
            UpdateHeadsetOffHeadFlag();
            if (displayNameInput != null) displayNameInput.interactable = IsKeyboardAvailable();
            if (joinCodeInput != null) joinCodeInput.interactable = IsKeyboardAvailable();
            yield return wait;
        }
    }

    // Confirmed directly by the user, and by reading OpenWorldsVRManager.cs's own
    // checkHeadsetPresence()/CheckMovement() (~L3441-3537): the stationary-timer-based detection
    // the SDK ships (has the raw head-tracking position stayed unchanged for stationaryThreshold
    // seconds) IS the reliable, proven mechanism here, deliberately chosen over an XR feature
    // query (CommonUsages.userPresence) specifically because that feature doesn't reliably
    // report on real hardware/runtimes. Two earlier versions of this method got this backwards:
    // first trying isValid alone (too eager -- true the instant a headset is merely connected,
    // not worn), then trying userPresence (the thing OpenWorldsVR's own author avoided), both
    // re-deriving offHead every poll and overwriting isHeadsetOffHead unconditionally -- which
    // actively fought CheckMovement's own transitions (confirmed live: a captured log showed
    // CheckMovement repeatedly re-detecting "OFF Head" because this method kept flipping the flag
    // back to false in between, and separately, suppressing CheckMovement outright via
    // reflection to stop that fight made off-head detection never fire at all). Both reverted.
    //
    // This method no longer re-derives offHead from any XR feature. It trusts
    // checkHeadsetPresence/CheckMovement entirely, and only ever forces the flag in ONE
    // unambiguous direction: true, when there is no head-tracking device at all
    // (GetDeviceAtXRNode(Head).isValid false) -- CheckMovement's own loop can't self-heal from
    // this case (its TryGetFeatureValue calls just silently fail and it skips the tick rather
    // than transitioning), so a fully-disconnected device, or a NETCRAFTER_VR_DESKTOP_ONLY build
    // (XR never initialized at all) would otherwise leave isHeadsetOffHead stuck at whatever it
    // last was. It is never forced back to false here -- once a real device is present, deciding
    // on/off-head is left entirely to the SDK's own mechanism, so this can only ever add
    // coverage for a gap the SDK has, never contradict a decision it already made. Matches the
    // same narrow, one-purpose intent NetCrafter Pro's own VRNetworkManager.cs documents for the
    // identical problem, just one-directional instead of bidirectional specifically to guarantee
    // this can never re-fight CheckMovement the way the reverted attempts did.
    //
    // SetFollowersEnabled below is purely reactive to whatever isHeadsetOffHead's CURRENT value
    // is (regardless of whether this method or CheckMovement/checkHeadsetPresence set it) -- it's
    // this project's own addition on top of the SDK (HeadFollower/LHandFollower/RHandFollower
    // free-running on stale data otherwise), which neither OpenWorldsVR nor NetCrafter Pro's
    // architecture needs, so the SDK has no reason to manage it itself.
    private void UpdateHeadsetOffHeadFlag()
    {
#if NETCRAFTER_VR_EXAMPLE
        var manager = OpenWorldsVRManager.Instance;
        if (manager == null) return;

        if (!UnityEngine.XR.InputDevices.GetDeviceAtXRNode(UnityEngine.XR.XRNode.Head).isValid)
        {
            if (!manager.isHeadsetOffHead) manager.PlayerIKOff();
            manager.isHeadsetOffHead = true;
        }

        bool offHead = manager.isHeadsetOffHead;
        bool changed = !_hasKnownOffHeadOnce || offHead != _lastKnownOffHead;
        _lastKnownOffHead = offHead;
        _hasKnownOffHeadOnce = true;

        if (changed) SetFollowersEnabled(!offHead);
#endif
    }

#if NETCRAFTER_VR_EXAMPLE
    private bool _lastKnownOffHead;
    private bool _hasKnownOffHeadOnce;
#endif

    // Confirmed live: PlayerIKOff() only tells the IK solver to stop RESOLVING toward the head/
    // hand targets -- it does nothing to HeadFollower/LHandFollower/RHandFollower themselves,
    // which keep running their own LateUpdate() every frame regardless, continuously deriving a
    // new local position/rotation from the XR camera rig's transform. With no headset connected
    // that transform isn't being driven by any real tracking data, so the followers free-run on
    // whatever stale/default pose the XR plugin leaves it at -- and because these same followers
    // carry the VRHeadPosition/VRHeadRotation/etc. NetCrafterSyncBinding components (Part 7.3),
    // that garbage gets synced to every other player exactly like real tracking data would,
    // independent of whether local IK is on or off. Disabling the follower components themselves
    // on a headset-off transition stops them from producing (and syncing) that garbage at all --
    // they simply hold their last real position/rotation, which NetCrafterSyncBinding then just
    // keeps re-sending unchanged (harmless; see SyncRuleDefinition's OnChange backstop). Walking/
    // animation/rotation are untouched by this: Move()/PlayerRotate()/AnimatePlayer() all read
    // from the player root and its own input state, never from these followers.
    private void SetFollowersEnabled(bool enabled)
    {
#if NETCRAFTER_VR_EXAMPLE
        if (_headFollower != null) _headFollower.enabled = enabled;
        if (_lHandFollower != null) _lHandFollower.enabled = enabled;
        if (_rHandFollower != null) _rHandFollower.enabled = enabled;
#endif
    }

    private static bool IsKeyboardAvailable()
    {
#if NETCRAFTER_VR_EXAMPLE
        bool offHead = OpenWorldsVRManager.Instance != null && OpenWorldsVRManager.Instance.isHeadsetOffHead;
        bool noHeadset = !UnityEngine.XR.InputDevices.GetDeviceAtXRNode(UnityEngine.XR.XRNode.Head).isValid;
        return offHead || noHeadset;
#else
        return true; // No OpenWorldsVR present yet -- treat as always-desktop so the demo is still usable for wiring/testing.
#endif
    }

    public void OnLoginClicked()
    {
        Debug.Log("[VRDemo] Login clicked, display name: " + displayNameInput.text);
        displayName = string.IsNullOrWhiteSpace(displayNameInput.text) ? "Player" + Random.Range(100, 1000) : displayNameInput.text.Trim();   // unique default, so two blank names can be told apart
        ShowLobby();
    }

    public void OnHostClicked()
    {
        if (statusText != null) statusText.text = "";
        if (relay.IsConnected) return;   // already in a session -- don't reset it
        relay.UpdateHost("");   // host, even if a failed join left a code behind
        if (relayConnectionManagerObject.activeSelf) relay.Connect();
        else relayConnectionManagerObject.SetActive(true);
    }

    private Coroutine _loginRoutine;

    public void OnJoinClicked()
    {
        string code = joinCodeInput.text.Trim();
        if (string.IsNullOrEmpty(code)) return;
        if (statusText != null) statusText.text = "";
        _currentJoinCode = code.ToUpperInvariant();
        relay.UpdateHost(code);
        // Already active after a failed attempt (e.g. a mistyped code): SetActive(true) would do
        // nothing, so start the new attempt directly. Connect() ignores the call if one is running.
        if (relayConnectionManagerObject.activeSelf) relay.Connect();
        else relayConnectionManagerObject.SetActive(true);
        if (_loginRoutine != null) StopCoroutine(_loginRoutine);   // the failed attempt's wait
        _loginRoutine = StartCoroutine(SendLoginWhenConnected());
    }

    private void OnRelayHosting(object joinCodeObj)
    {
        joinCodeDisplay.text = "Join code: " + (string)joinCodeObj;
        _currentJoinCode = (string)joinCodeObj;
        StartCoroutine(SendLoginWhenConnected());
    }

    private void OnConnectionLost(object reason)
    {
        Debug.Log("[VRDemo] Connection lost: " + reason);
        if (statusText != null)
            statusText.text = NetCrafterConnectionStatus.ToPlayerMessage((string)reason);
    }

    private void OnRelayStatus(object message)
    {
        if (statusText != null) statusText.text = (string)message;
    }

    private const float HostLobbyDisplaySeconds = 4f;

    // Confirmed live: the rendezvous lookup alone can retry up to 3 times at 15s each on a slow
    // or flaky connection (RelayConnectionManager's RendezvousRequestTimeoutSeconds/
    // maxJoinAttempts) before TURN permissions and the hello/ack handshake even start -- a
    // real-network join can take well over 10 seconds without anything actually being wrong.
    private const float ConnectTimeoutSeconds = 60f;

    private IEnumerator SendLoginWhenConnected()
    {
        float deadline = Time.realtimeSinceStartup + ConnectTimeoutSeconds;
        while (!relay.IsConnected && Time.realtimeSinceStartup < deadline) yield return null;
        if (!relay.IsConnected) { Debug.LogError($"[VRDemo] Failed to connect within {ConnectTimeoutSeconds}s."); yield break; }

        if (relay.IsHost)
        {
            int colorIndex = relay.LocalUserId % 8;
            int spawnIndex = relay.LocalUserId % 4;
            VRGameState.Players[relay.LocalUserId] = new VRGameState.PlayerInfo
            {
                displayName = displayName, colorIndex = colorIndex, spawnIndex = spawnIndex
            };
            relay.OnPeerDisconnected += OnHostDetectedPeerDisconnected;
            yield return new WaitForSeconds(HostLobbyDisplaySeconds);
        }
        else
        {
            // Confirmed necessary in the Racing tutorial: without this, a joiner never learns
            // the host itself has disconnected -- only the host branch above ever subscribed.
            // See OnJoinerDetectedHostDisconnected for why this is symmetric with
            // OnHostDetectedPeerDisconnected despite there being no BroadcastToAll here.
            relay.OnPeerDisconnected += OnJoinerDetectedHostDisconnected;
            new LoginRequest { displayName = displayName }.Send(relay);
        }

        RefreshPlayerList();
        ShowGameplay();
        StartCoroutine(ConfigureLocalPlayerWhenReady());
    }

    // ──── Local player setup (OpenWorldsVR-dependent) ──────────────────────────────────────

    // OpenWorldsVRManager.Instance.player is only assigned once the player actively picks a
    // character in OpenWorldsVR's own character-selection panel -- not automatically on scene
    // start or on joining, and nothing here forces a default: this waits exactly as long as it
    // takes, the same as the SFS3 tutorial's own VRNetworkManager
    // (while (OpenWorldsVRManager.Instance.player == null) yield return null; -- no timeout, no
    // fallback LoadPrefab() call). Deliberately simpler than an earlier version of this method,
    // which called LoadPrefab(0) itself if the player hadn't picked one by the time Login/Lobby
    // finished -- removed once it became clear the SFS3 approach (just wait) was the cleaner
    // design, not something NetCrafter Relay needed to improve on.
    // HeadFollower/LHandFollower/RHandFollower are scene-level singletons (NOT children of the
    // player) that OpenWorldsVRManager also activates asynchronously a short time after player
    // assignment. This waits for all of them, then configures every local NetCrafterSyncBinding
    // -- the player root's own two (position/rotation) plus the two each on the three follower
    // singletons (eight bindings total) -- under the local player id, matching the "pre-placed,
    // disabled until Configure()" pattern every other Relay tutorial uses. See Tutorial_VR.html
    // Part A3/B1 for why head/hand sync targets the followers directly (world-space
    // Transform_Position/Rotation) instead of the SFS3 tutorial's manual player-relative float
    // packing.
    private IEnumerator ConfigureLocalPlayerWhenReady()
    {
#if NETCRAFTER_VR_EXAMPLE
        while (OpenWorldsVRManager.Instance == null || OpenWorldsVRManager.Instance.player == null)
            yield return null;

        GameObject player = OpenWorldsVRManager.Instance.player;
        int myId = relay.LocalUserId;

        _localRootBindings = player.GetComponents<NetCrafterSyncBinding>();
        foreach (var binding in _localRootBindings) { binding.Configure(myId, true); binding.enabled = true; }
        WarnIfRootBindingsMissing(player, _localRootBindings);

        var colorMgr = player.GetComponent<VRColorManager>();
        colorMgr?.SetColor(relay.LocalUserId % 8);

        var nameBadge = player.GetComponentInChildren<PlayerNameDisplay>(true);
        if (nameBadge != null) nameBadge.Hide(); // you don't need to see your own name tag

        float followerWaitStart = Time.time;
        HeadFollower headFollower = null;
        LHandFollower lHandFollower = null;
        RHandFollower rHandFollower = null;
        while (headFollower == null || lHandFollower == null || rHandFollower == null)
        {
            headFollower  = FindAnyObjectByType<HeadFollower>();
            lHandFollower = FindAnyObjectByType<LHandFollower>();
            rHandFollower = FindAnyObjectByType<RHandFollower>();
            if (headFollower != null && lHandFollower != null && rHandFollower != null) break;
            if (Time.time - followerWaitStart > 3f)
            {
                Debug.LogError("[VRDemo] HeadFollower/LHandFollower/RHandFollower not active after 3s — " +
                    "head/hand sync bindings on them will not be configured. Confirm OpenWorldsVRManager " +
                    "spawned the player correctly.");
                break;
            }
            yield return new WaitForSeconds(0.1f);
        }

        foreach (var t in new[] { headFollower?.transform, lHandFollower?.transform, rHandFollower?.transform })
        {
            if (t == null) continue;
            foreach (var binding in t.GetComponents<NetCrafterSyncBinding>())
            {
                binding.Configure(myId, true);
                binding.enabled = true;
            }
        }

        // Cached so UpdateHeadsetOffHeadFlag can enable/disable these on a headset state change
        // from here on -- see SetFollowersEnabled for why that matters. Synced to the CURRENT
        // isHeadsetOffHead value immediately (not just left for the next change event): if the
        // headset was already off when this coroutine finishes (the common desktop-testing case,
        // where isHeadsetOffHead flips to true once, on the very first poll in Start(), long
        // before these fields exist to disable), there is no later "change" to react to and the
        // followers would otherwise run with stale/garbage tracking data for the rest of the
        // session.
        _headFollower = headFollower;
        _lHandFollower = lHandFollower;
        _rHandFollower = rHandFollower;
        SetFollowersEnabled(!OpenWorldsVRManager.Instance.isHeadsetOffHead);

        StartCoroutine(PollStatusChanges(player));
#else
        Debug.LogWarning("[VRDemo] NETCRAFTER_VR_EXAMPLE is not defined — OpenWorldsVR is not " +
            "imported/enabled, so the local player's head/hand/root sync bindings were never " +
            "configured. See the tutorial doc's Part A1.");
        yield break;
#endif
    }

    // Confirmed live: a buyer-added custom character model (OpenWorldsVRManager.ListofPlayerModels
    // is explicitly designed to be extended with your own entries) doesn't automatically get this
    // tutorial's own root sync bindings just by being added there -- NetCrafterSyncBinding has to
    // be wired onto ITS root too, the same as every shipped LabMan1-4 model already is (GameObject
    // → NetCrafter Relay → Auto-Wire VR Local Player Root, one click). Without this check that gap
    // is silent: with zero root bindings, Configure() above has nothing to configure, so this
    // player's position/rotation never gets sent to anyone -- no exception, no visible symptom
    // locally, just a frozen avatar on every OTHER client's screen.
    private static void WarnIfRootBindingsMissing(GameObject player, NetCrafterSyncBinding[] bindings)
    {
        bool hasPosition = false, hasRotation = false;
        foreach (var b in bindings)
        {
            var ruleName = b.Rule?.ruleName;
            if (ruleName == "VRRootPosition") hasPosition = true;
            else if (ruleName == "VRRootRotation") hasRotation = true;
        }

        if (hasPosition && hasRotation) return;

        string missing = !hasPosition && !hasRotation ? "VRRootPosition and VRRootRotation"
            : !hasPosition ? "VRRootPosition" : "VRRootRotation";

        Debug.LogError($"[VRDemo] '{player.name}' is missing a NetCrafterSyncBinding for {missing} " +
            "-- its position/rotation will never be sent to other players. If this is a custom " +
            "character model added to OpenWorldsVRManager's own character list, wire it the same " +
            "way as the shipped models: select its root and run GameObject → NetCrafter Relay → " +
            "Auto-Wire VR Local Player Root (Tutorial_VR.html Part 7.2).");
    }

    // Edge-triggered: animState/grounded/isDesktopMode only change occasionally (a handful of
    // times a second at most, usually far less), unlike head/hand/root transforms which change
    // every frame — these go through a schema message (RequestPlayerStatus/PlayerStatusUpdate)
    // instead of a continuous sync rule, sent only when something actually changes rather than
    // on a fixed cadence. There is no Animator_Int sync target in NetCrafterSyncBinding (only
    // Animator_Float/Animator_Bool), and animState's discrete 0-10 range doesn't fit either
    // cleanly — an event-style message fits its actual update frequency better anyway.
    private IEnumerator PollStatusChanges(GameObject player)
    {
#if NETCRAFTER_VR_EXAMPLE
        var wait = new WaitForSeconds(StatusPollInterval);
        while (true)
        {
            yield return wait;
            if (player == null) yield break;

            var anim = player.GetComponent<Animator>();
            int animState = GetAnimState(anim);
            bool grounded = anim != null && anim.isActiveAndEnabled && anim.runtimeAnimatorController != null && anim.GetBool("Grounded");
            bool isDesktopMode = OpenWorldsVRManager.Instance == null || OpenWorldsVRManager.Instance.isHeadsetOffHead;

            bool changed = !_hasSentStatusOnce || animState != _lastSentAnimState || grounded != _lastSentGrounded || isDesktopMode != _lastSentIsDesktopMode;
            bool backstopDue = _hasSentStatusOnce && (Time.time - _lastStatusSendTime) >= StatusBackstopInterval;
            if (!changed && !backstopDue)
                continue;

            _lastSentAnimState = animState;
            _lastSentGrounded = grounded;
            _lastSentIsDesktopMode = isDesktopMode;
            _hasSentStatusOnce = true;
            _lastStatusSendTime = Time.time;

            if (relay.IsHost)
            {
                var ev = new PlayerStatusUpdateEvent { playerId = relay.LocalUserId, animState = animState, grounded = grounded, isDesktopMode = isDesktopMode };
                relay.BroadcastToAll("PlayerStatusUpdate", ev.Serialize(), true);
            }
            else
            {
                new RequestPlayerStatusRequest { animState = animState, grounded = grounded, isDesktopMode = isDesktopMode }.Send(relay);
            }
        }
#else
        yield break;
#endif
    }

    // OpenWorldsVR_Animator.controller has no float parameters -- locomotion is a set of
    // discrete, mutually-exclusive per-direction bools (WalkForward, RunForward, ...),
    // always cleared before the new active one is set, so at most one is ever true. Maps that
    // onto a single wire-friendly int. Confirmed against OpenWorldsVRManager.cs directly (not
    // guessed) — see Tutorial_VR.html Part A3 for the full value table.
    private static int GetAnimState(Animator anim)
    {
        if (anim == null || anim.runtimeAnimatorController == null || !anim.isActiveAndEnabled) return 0;
        if (anim.GetBool("RunForward"))   return 5;
        if (anim.GetBool("RunBackward"))  return 6;
        if (anim.GetBool("RunLeft"))      return 7;
        if (anim.GetBool("RunRight"))     return 8;
        if (anim.GetBool("WalkForward"))  return 1;
        if (anim.GetBool("WalkBackward")) return 2;
        if (anim.GetBool("WalkLeft"))     return 3;
        if (anim.GetBool("WalkRight"))    return 4;
        if (anim.GetBool("InAir"))        return 9;
        if (anim.GetBool("JumpLand"))     return 10;
        return 0;
    }

    // ──── Disconnect handling ───────────────────────────────────────────────────────────────

    private void OnHostDetectedPeerDisconnected(int peerId)
    {
        var left = new PlayerLeftEvent { playerId = peerId };
        relay.BroadcastToAll("PlayerLeft", left.Serialize(), true);
        OnPlayerLeftReceived(peerId);
    }

    // Joiner-only counterpart to OnHostDetectedPeerDisconnected above. A joiner's only peer is
    // always the host, and RelayConnectionManager always fires OnPeerDisconnected with id 0 for
    // a joiner -- which lines up exactly with the host's own relay.LocalUserId of 0 (always
    // true, see RelayConnectionManager's HostSession). There's nothing to BroadcastToAll here --
    // a joiner never relays to other joiners at all (host-relayed star), and with the host gone
    // there is nobody left to relay to regardless.
    private void OnJoinerDetectedHostDisconnected(int peerId)
    {
        OnPlayerLeftReceived(peerId);
        if (statusText != null) statusText.text = "Host disconnected — connection lost.";
    }

    // ──── Incoming schema events (wired via NetCrafterSceneEventRouter) ────────────────────

    public void OnPlayerJoinedReceived()
    {
        var ev = (PlayerJoinedEvent)NetCrafterSceneEventRouter.Instance.GetLastPayload("PlayerJoined");
        VRGameState.Players[ev.playerId] = new VRGameState.PlayerInfo
        {
            displayName = ev.displayName, colorIndex = ev.colorIndex, spawnIndex = ev.spawnIndex
        };

        if (ev.playerId != relay.LocalUserId)
            SpawnOrUpdateRemote(ev.playerId, ev.displayName, ev.colorIndex);

        RefreshPlayerList();
    }

    // Called directly from HandleLogin's Custom Host Code -- only on the process actually
    // hosting the session, and only for a player OTHER than the host itself. BroadcastToAll
    // never loops back to the host's own incoming-message pipeline, so without this direct
    // call the host would never see remote avatars for its own joiners.
    public void HostRegisterPlayerLocally(int playerId, string displayNameForPlayer, int colorIndex, int spawnIndex)
    {
        VRGameState.Players[playerId] = new VRGameState.PlayerInfo
        {
            displayName = displayNameForPlayer, colorIndex = colorIndex, spawnIndex = spawnIndex
        };
        if (playerId != relay.LocalUserId)
            SpawnOrUpdateRemote(playerId, displayNameForPlayer, colorIndex);
        RefreshPlayerList();
    }

    private void SpawnOrUpdateRemote(int playerId, string displayNameForRemote, int colorIndex)
    {
        if (_remoteCharacters.TryGetValue(playerId, out var existing))
        {
            existing.GetComponentInChildren<PlayerNameDisplay>()?.SetName(displayNameForRemote);
            existing.GetComponent<VRColorManager>()?.SetColor(colorIndex);
            return;
        }

        var instance = Instantiate(remoteCharacterPrefab);
        instance.name = "RemoteVRCharacter_" + playerId;

        // Root bindings live directly on the instantiated root; head/hand bindings live on the
        // RemoteHeadTarget/RemoteLHandTarget/RemoteRHandTarget children RemoteVRCharacterController
        // creates in its own Awake() (which runs on Instantiate, before this line) -- covered by
        // GetComponentsInChildren.
        foreach (var binding in instance.GetComponentsInChildren<NetCrafterSyncBinding>(true))
        {
            binding.Configure(playerId, false);
            binding.enabled = true;
        }

        instance.GetComponent<VRColorManager>()?.SetColor(colorIndex);

        var nameDisplay = instance.GetComponentInChildren<PlayerNameDisplay>();
        if (nameDisplay != null) nameDisplay.SetName(displayNameForRemote);

        _remoteCharacters[playerId] = instance;
        _remotePlayerNames[playerId] = displayNameForRemote;
    }

    public void OnPlayerStatusUpdateReceived()
    {
        var ev = (PlayerStatusUpdateEvent)NetCrafterSceneEventRouter.Instance.GetLastPayload("PlayerStatusUpdate");
        if (!_remoteCharacters.TryGetValue(ev.playerId, out var remoteGo) || remoteGo == null) return;
        remoteGo.GetComponent<RemoteVRCharacterController>()?.ApplyStatus(ev.animState, ev.grounded, ev.isDesktopMode);
    }

    public void OnPlayerLeftReceived(int playerId)
    {
        VRGameState.Players.Remove(playerId);
        if (_remoteCharacters.TryGetValue(playerId, out var instance))
        {
            if (instance != null) Destroy(instance);
            _remoteCharacters.Remove(playerId);
        }
        _remotePlayerNames.Remove(playerId);
        RefreshPlayerList();
    }

    public void OnPlayerLeftBroadcastReceived()
    {
        var ev = (PlayerLeftEvent)NetCrafterSceneEventRouter.Instance.GetLastPayload("PlayerLeft");
        OnPlayerLeftReceived(ev.playerId);
    }

    private void RefreshPlayerList()
    {
        var sb = new StringBuilder();
        foreach (var kv in VRGameState.Players)
            sb.AppendLine(kv.Value.displayName);
        if (playerListText != null) playerListText.text = sb.ToString();
    }
}
}

Confirmed live in every other tutorial, and unchanged here: a departed player's avatar stays behind forever if the departing player was the HOST, not a joiner — unless both sides of disconnect detection are wired. The host branch of SendLoginWhenConnected() subscribes to OnPeerDisconnected so the host can broadcast PlayerLeft. The joiner branch subscribes too — a joiner's only peer is always the host (always network id 0), so OnPeerDisconnected firing there reuses the same cleanup a PlayerLeft broadcast would have triggered, plus a StatusText message, since this is the whole session ending, not just one fewer player. There's no host migration — a known, disclosed limitation, same as every other tutorial.

09

Part 8 — Run it#

This part could not be verified on real hardware while writing this tutorial — see the confidence note at the end of this document. Everything through a clean compile and careful code reading has been confirmed; actually standing in a headset next to another tracked player has not.

  1. Run one copy — the host, headset on. Enter a name, Continue, Host Game. Confirm the Lobby panel (a world-space canvas, readable at arm's length) shows a join code.
  2. Run 1–3 more copies — joiners (headset or desktop/isDesktopMode fallback). Enter a name, Continue, type in the join code, Join Game.
  3. On every client, confirm:
    • Every other connected player's avatar appears, correctly coloured (colorIndex), with a readable name tag that stays upright and doesn't fight the avatar's own rotation.
    • Another player's head and hand movements show up live on your screen — not just a position jump every half-second, actual smooth tracked movement.
    • Walking, running in different directions, jumping, and landing all show the matching animation on every other client (Part 3.4's animState table).
    • Taking a headset off (or toggling isDesktopMode for testing) makes that player's remote avatar stop reaching toward stale head/hand positions on everyone else's screen, rather than freezing mid-gesture.
  4. Quit one joiner. Straight away (a quitting game says goodbye; if it crashes instead, the host notices after about 15 seconds of silence), that avatar disappears from every remaining client and the player list drops them.
  5. With at least one joiner still connected, quit the host instead. Straight away (or after about 15 seconds if the host crashed), each remaining joiner's StatusText shows "Host disconnected — connection lost." and the host's own now-frozen avatar disappears from their scene.

If hosting or joining fails outright, StatusText on the Lobby panel shows a plain-language message instead of a silent, unexplained Lobby screen. If avatars appear but never move, see Common Mistakes before assuming the network itself is broken.

Mistype a join code on purpose, then correct it and press Join again: the new attempt connects (since 2.0; before, a failed attempt left the button doing nothing). During play the join code stays on screen (top-right corner of the floating panel) so anyone can read it out to a friend.

10

Common mistakes#

A Host Action's Custom Host Code never shows up in the generated output. Confirmed directly while building this tutorial's own HandleLogin — Logic Type must be Custom. BroadcastAll/SenderOnly/TargetUser never read the Custom Host Code field at all, with no warning that it was ignored. If a Host Action genuinely needs custom logic beyond auto-matched fields, double-check Logic Type before assuming the generator is broken.

The demo compiles and the Login/Lobby flow works, but no VR player ever gets configured. NETCRAFTER_VR_EXAMPLE isn't defined (Part 7.7) — either OpenWorlds VR isn't imported yet, or the define wasn't added after it was. Check the Console for [VRDemo] NETCRAFTER_VR_EXAMPLE is not defined warnings.

Merging this tutorial's Login/Lobby UI directly into OpenWorlds VR's own sample scene (rather than building a scene from scratch): Login/Lobby buttons visibly react to clicks (hover/pressed color changes normally) but onClick never fires — no log, no error, completely silent, while an InputField's own Submit-on-Enter still works fine on the same canvas. Confirmed live, traced into XR Interaction Toolkit's own UIInputModule.ProcessPointerButton(): a Selectable's pointer-down/up visual feedback always fires on whatever was actually pressed, unconditionally — but onClick only fires if that same object is also what a freshly recomputed raycast resolves to at release time. Once OpenWorlds VR's own XR interaction machinery is live in the scene, those two stop agreeing, silently. Two things to check, both load-bearing: Show Selector On Start on the OpenWorldsVRManager component should be checked (see the Prerequisites-adjacent note above) so a player doesn't spawn, and its interactors don't activate, before your own Login/Lobby flow has finished — this tutorial's VRDemoController.ConfigureLocalPlayerWhenReady() simply waits for OpenWorldsVRManager.Instance.player to become non-null, the same way the SFS3 tutorial's own VRNetworkManager does, rather than forcing a default model itself (Part 7). Second, and the part that actually fixes the click itself: every Login/Lobby button in this scene has a ClickOnPointerDown component added — it fires on IPointerDownHandler directly, the same mechanism an InputField already uses to gain focus, sidestepping the press/release mismatch entirely instead of depending on it. Remove each button's onClick wiring once ClickOnPointerDown is in place — confirmed live, leaving both wired to the same handler caused the handler to run twice for a single click often enough to matter: onClick isn't reliably suppressed by the mismatch above, just inconsistent, so some clicks fired both, starting two overlapping connect/spawn sequences and throwing a NullReferenceException deep in OpenWorlds VR's own per-frame character-controller code as they raced. Add ClickOnPointerDown (and remove onClick) on any button that stops responding the same way in a scene like this.

Same merged-scene setup, a different symptom: the desktop mouse cursor disappears somewhere around Login/Lobby, with only the Unity Editor's own Escape-releases-cursor-lock behavior (Play Mode only, not present in a real build) bringing it back. Confirmed live — unrelated to the click bug above. OpenWorldsVRManager's own FadeIn()/FadeOut() (driving its character-selection panel's fade animation in and out as it's shown, and again once the player actually picks a character) unlock and lock Cursor.lockState directly, on a schedule that has nothing to do with which of this tutorial's own panels is active — and since the panel is genuinely interactive the whole time Login/Lobby are showing (Part 7.7), a player clicking a character at any point, even before finishing Login, can trigger this. VRDemoController.Update() re-asserts an unlocked, visible cursor every single frame while gameplayPanel isn't active, so OpenWorlds VR's own fade timers can never leave the cursor stuck hidden behind Login or Lobby — left alone during actual Gameplay, since cursor lock for desktop/PCtoVR mouselook at that point is OpenWorlds VR's own concern, not this controller's.

A remote avatar's head/hands don't move at all, but its root does. Check that all six NetCrafterSyncBinding → Rule fields on RemoteVRCharacterPrefab's HeadTarget/LHandTarget/RHandTarget children are actually assigned (Part 7.4, Step 4) — an unassigned rule self-disables with a Console warning, same failure mode as every other tutorial. Also confirm RemoteVRCharacterController's Head Target/L Hand Target/R Hand Target fields are wired — if they're null, it logs an error and skips adding PlayerIKSolver entirely.

The name tag spins or jitters as the avatar turns. PlayerNameDisplay must billboard the NameCanvas child, never the avatar root — billboarding the root fights the root's own synced rotation every frame, with no error ever logged. See Part 7.4, Step 5.

Joiners see each other's avatars fine, but the host sees no one. Confirmed pattern from every other tutorial in this package — this is what happens without HandleLogin's HostRegisterPlayerLocally call (Part 4.1). BroadcastToAll never loops back to the host's own incoming-message pipeline, so the host's OnPlayerJoinedReceived() never fires for anyone.

NullReferenceException clicking Host Game or Join Game. Same cause as every other tutorial: the RelayConnectionManager GameObject's component is a different schema's generated class, most likely from copying a GameObject/prefab out of another tutorial's scene instead of this one. Delete it and re-add via Scenes → Scene Assistant → Add to Existing Scene.

Keyboard-entry fields (name/join code) can't be focused while wearing a headset. By design, not a bug — IsKeyboardAvailable() checks isHeadsetOffHead and the XR head node's tracking validity, and only enables those input fields when neither is tracking. Take the headset off (or test in desktop/isDesktopMode fallback) to type.

Testing two players on one physical machine (one Editor instance, one built player) with a real headset plugged in produces unpredictable tracking/input in both instances. Confirmed live — a single headset can't be cleanly shared between two processes both trying to claim it through the same XR runtime. Use GameObject → NetCrafter Relay → Build Desktop-Only VR Demo Player... to produce a genuinely separate build that never initializes XR at all — it temporarily disables XR Plug-in Management's "Initialize XR on Startup" and adds the NETCRAFTER_VR_DESKTOP_ONLY define for that one build only, then restores your project's own (headset-aware) settings afterward, whether the build succeeds or fails. Run that build alongside your normal Editor instance (which keeps the real headset) with no contention, or hand it to a tester who doesn't own a headset at all — remote avatars still react correctly to other players' real VR state either way, since that's driven entirely by network data (isDesktopMode), never by this machine's own XR hardware.

11

What's Next#

FeatureDescription
Voice chatLayer a Reliable/Unreliable audio-chunk message or a dedicated voice SDK on top of the existing Login/Lobby flow
Hand-gesture pickupsA grab/release trigger following Co-op's host-authoritative TryCollectPickup pattern, keyed off hand-collider overlap instead of a 2D/3D trigger
Teleport locomotion syncIf your OpenWorlds VR setup uses teleport rather than continuous movement, consider OnChange-only sync (no backstop interval) for the root rule, since a teleport is a single large discrete jump, not continuous motion
Per-hand grip stateA grounded-style bool per hand (gripping/open), same edge-triggered message pattern as animState
Spectator/non-VR viewerA screen-space camera following the action, reusing the same PlayerJoined/PlayerStatusUpdate broadcasts a VR client already receives

Tutorial by Pivec Labs — NetCrafter Relay