by Pivec Labs
Tutorial Multiplayer Racing

NetCrafter Relay — Racing Tutorial

Build a host-relayed multiplayer racing game with real-time car sync and a host-authoritative lap system.

By Pivec Labs

Time: 90–120 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); TextMeshPro essentials imported (Window → TextMeshPro → Import TMP Essentials, click Import when prompted); ARCADE: FREE Racing Car imported from the Unity Asset Store (search "ARCADE Free Racing Car" by Mena). Recommended (not required): read the Chat Quick Start and 2-4 Player Co-op Arena 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 oval track where every connected player drives a physics-based car — position and rotation replicated live to every other client — with a host-authoritative lap counter and a live leaderboard. This is the most advanced of NetCrafter Relay's tutorials: it's the only one built around time-based, host-validated scoring rather than one-shot events (Chat's messages) or simple collision pickups (Co-op).

Free packages this demo uses (not included with NetCrafter Relay — import them yourself from the Asset Store): ARCADE - FREE Racing Car and Cartoon Tracks Pack 1 for the car and track. Without them the rest of NetCrafter Relay still compiles; the scene just shows missing models.

01

Part 0 — What's different about this tutorial#

Racing reuses everything Chat/Co-op/Character already established — Login → Lobby (real join code, Host/Join) → Gameplay, RelayConnectionManager, sync rules for continuous transform replication, NetCrafterEventDispatcher for framework events, Scene Events for schema events — without changing any of it. Two things are genuinely new:

  1. A lap system that's host-authoritative for a reason that isn't obvious upfront. A player's own client detects when their own car crosses the finish line (a trigger collider, purely local), but it doesn't just display "Lap 2" — it requests the host record the lap. The host is the only place a lap actually gets counted (RacingGameState.TryRecordLap), the same "one authority decides, everyone reacts to the broadcast" shape as Co-op's pickups, just guarding against an implausibly-fast repeat instead of an exact duplicate — see Part 4.
  2. Two sync rules on one car, not six driving one character (compare Character's tutorial): Transform_Position and Transform_Rotation move the car — that's all. There's no Rigidbody_Velocity/CarVelocity sync rule; the remote wheel-spin visual is approximated entirely from position delta between frames instead (Part 1.5), which sidesteps a kinematic remote Rigidbody's own velocity never reflecting transform-driven movement in the first place. Covered in full in Part 7.
02

Part 1 — Single-player setup#

This part has nothing to do with networking yet — it gets a drivable car on a track, entirely locally. Skip ahead to Part 2 if you already have one.

1.1 Import the track

The track is a ready-made environment package, not something you build by hand in this tutorial.

  1. Get Cartoon Race Track - Oval by RCC Design from the Unity Asset Store. Confirmed at time of writing: this is a free asset (Standard Unity Asset Store EULA, Extension Asset license) — add it to your account from the web store page, then in Unity's Package Manager, switch the source dropdown to My Assets, find it in the list, and click Import.
  2. Drag the track prefab into your scene from wherever the package places it in the Project window (the exact folder name depends on the package version — look for an RCC or Cartoon Race Track folder). Position it at world origin (0, 0, 0).

Check for magenta/pink materials immediately after import — this is the single most common point of confusion with any imported environment package, not just this one. The Asset Store listing's own compatibility table lists this package as supporting Built-in, URP, and HDRP — but that table reflects what the publisher has tagged, not a guarantee every material's shader was actually authored for whichever pipeline your project uses. This project uses URP (confirmed in Edit → Project Settings → Graphics — a Universal Render Pipeline asset is assigned). If any part of the track renders solid magenta/pink after import, that's Unity's unmistakable "missing shader" signal, and the fix is one step: Window → Rendering → Render Pipeline Converter (Unity 6) — or Edit → Render Pipeline → Universal Render Pipeline → Upgrade Project Materials on older Unity versions — run the Built-in-to-URP material upgrade, pointed at the track's own material folder. Do this before moving on to placing the car or checkpoints; a magenta track makes it much harder to see where anything actually is.

3. Look at the track's own hierarchy before continuing to Part 1.4 — you'll need to know where its start/finish line actually is to place the local car and (in Part 7.3) the lap checkpoint trigger. Package contents vary by version; if the track ships its own spawn markers or a finish-line object, use those positions directly. If it doesn't, use the track's own visible start/finish line marker (every oval track package has one) as your reference point instead of a hardcoded coordinate — this tutorial can't give you an exact number for a package it doesn't ship.

1.2 Import the car

This tutorial's CarController.cs (Part 1.5) and CarCamera.cs (Part 1.6) — and CarColorManager.cs, attached later in Part 7 — are all built against one specific free car package. Nothing else in this doc tells you where to get it, so do this now, before Part 1.4 expects it to already be in the project.

  1. Get ARCADE: FREE Racing Car by Mena from the Unity Asset Store. Confirmed at time of writing: this is a free asset (Standard Unity Asset Store EULA, Extension Asset license) — add it to your account from the web store page, then in Unity's Package Manager, switch the source dropdown to My Assets, find it in the list, and click Import.
  2. In the Project window, find the package's main car prefab (exact folder name/prefab name may vary by version — look for a folder from the "ARCADE" or "Racing Car" package; there's normally just one obvious car prefab, not several to choose between). You'll drag this into your scene in Part 1.4 — nothing to do with it yet.

Same render-pipeline caveat as the track (Part 1.1): this package's own Asset Store listing shows Built-in and URP as compatible, HDRP as not — if you're on HDRP for some reason, this asset isn't the one to use. On URP (this project's pipeline), check for magenta/pink materials after import the same way you did for the track, and run the Render Pipeline Converter if you see any.

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.

1.4 Place the car

  1. Drag the ARCADE: FREE Racing Car prefab (Part 1.2) into the scene, at your track's start line. Right-click it → Prefab → Unpack Completely — see the warning in Part 7.2 for exactly why this matters before this tutorial is done with it; doing it now, before you've touched a single component, costs nothing and avoids the trap entirely.
  2. Rename the root GameObject LocalCar.
  3. Confirm the car's hierarchy has separate WheelCollider components (not just visual wheel meshes) — CarController (Part 1.5) expects to find WheelColliders to drive. If the imported prefab only has visual wheel meshes with no colliders, add four WheelCollider components as children of the car root, roughly at each wheel's position, matching the visual mesh radius.

1.5 Car Controller

Assets/PivecLabs/Examples/RacingDemo/Scripts/CarController.cs ships with the package — nothing to create here, this is what it contains:

Show CarController.csships with the package — nothing to type
C#
using UnityEngine;
using UnityEngine.InputSystem;

namespace PivecLabs.NetCrafterRelay.Examples.RacingDemo
{

// Drives ONE car -- WheelCollider physics apply only when this is the LOCAL player's car
// (HasAuthority). A remote car is driven entirely by its own NetCrafterSyncBinding
// components applying incoming position/rotation directly, never by this script's
// FixedUpdate() -- its Rigidbody is set kinematic and its WheelColliders disabled in
// Configure() so they can't fight that. Per Editor/CODING_NOTES.md: new Input System only,
// never legacy UnityEngine.Input, and always guard Keyboard.current for null.
public class CarController : MonoBehaviour
{
    [Header("Wheel Colliders")]
    public WheelCollider frontLeft;
    public WheelCollider frontRight;
    public WheelCollider rearLeft;
    public WheelCollider rearRight;

    [Header("Wheel Visuals (optional -- spin/steer animation only, no physics)")]
    public Transform frontLeftVisual;
    public Transform frontRightVisual;
    public Transform rearLeftVisual;
    public Transform rearRightVisual;

    [Header("Handling")]
    public float motorTorque = 1500f;
    public float maxSteerAngle = 30f;
    public float brakeTorque = 3000f;

    public bool HasAuthority { get; private set; }
    public int PlayerId { get; private set; }

    private Rigidbody _rb;
    private Vector3 _spawnPosition;
    private Quaternion _spawnRotation;
    private float _visualSpinDegrees;
    private Vector3 _lastRemotePosition;
    private float _lastRemoteYaw;
    private bool _haveLastRemotePosition;
    private float _remoteSteer;
    private float _wheelRadius = 0.37f;
    private float _wheelbase = 2.5f;
    private Quaternion _flBase = Quaternion.identity, _frBase = Quaternion.identity,
                       _rlBase = Quaternion.identity, _rrBase = Quaternion.identity;

    private void Awake()
    {
        _rb = GetComponent<Rigidbody>();
        _spawnPosition = transform.position;
        _spawnRotation = transform.rotation;

        // Remote wheel animation: each wheel's own resting rotation (left/right wheel models
        // are often built rotated), the wheel size, and the front-to-rear axle distance.
        if (frontLeftVisual != null) _flBase = frontLeftVisual.localRotation;
        if (frontRightVisual != null) _frBase = frontRightVisual.localRotation;
        if (rearLeftVisual != null) _rlBase = rearLeftVisual.localRotation;
        if (rearRightVisual != null) _rrBase = rearRightVisual.localRotation;
        var anyWheel = frontLeft != null ? frontLeft : rearLeft;
        if (anyWheel != null && anyWheel.radius > 0.05f) _wheelRadius = anyWheel.radius;
        if (frontLeftVisual != null && rearLeftVisual != null)
        {
            float wb = Mathf.Abs(transform.InverseTransformPoint(frontLeftVisual.position).z -
                                 transform.InverseTransformPoint(rearLeftVisual.position).z);
            if (wb > 0.5f) _wheelbase = wb;
        }

        // Recommended arcade-handling defaults, applied regardless of authority so a
        // remote car (about to be made kinematic below) still has sane values if it's ever
        // reconfigured back to local authority later (e.g. host migration is not supported
        // today, but nothing here assumes it never will be).
        if (_rb != null)
        {
            _rb.linearDamping = 0.1f;
            _rb.angularDamping = 3f;
            _rb.centerOfMass = new Vector3(0f, -0.5f, 0f);
            _rb.interpolation = RigidbodyInterpolation.Interpolate;
            _rb.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
        }
    }

    // Called by RacingDemoController once the local player's id is known (after login) --
    // assigns this car to a specific network player id and decides whether THIS client
    // drives it (true, applies WheelCollider physics from input) or only receives its
    // position/rotation via sync (false, no local physics simulation at all).
    public void Configure(int playerId, bool hasAuthority)
    {
        PlayerId = playerId;
        HasAuthority = hasAuthority;

        if (!hasAuthority)
        {
            // A remote car's transform is driven entirely by incoming sync data -- its own
            // Rigidbody/WheelCollider physics would fight that every FixedUpdate, the same
            // "a remote object has no business simulating its own local physics" reasoning
            // already documented on NetCrafterSyncBinding for Apply Root Motion.
            if (_rb != null)
            {
                _rb.isKinematic = true;
                // Interpolation only helps a physics-driven body. On this remote (sync-driven)
                // car it made Unity pull the Transform back toward the physics pose every frame,
                // undoing most of each synced move (measured: pushed 10 m, moved 3.5 m) -- the
                // car trailed where the other player really was, and its wheels under-spun.
                _rb.interpolation = RigidbodyInterpolation.None;
            }
            SetWheelCollidersEnabled(false);
        }
    }

    private void SetWheelCollidersEnabled(bool isEnabled)
    {
        if (frontLeft != null) frontLeft.enabled = isEnabled;
        if (frontRight != null) frontRight.enabled = isEnabled;
        if (rearLeft != null) rearLeft.enabled = isEnabled;
        if (rearRight != null) rearRight.enabled = isEnabled;
    }

    private void FixedUpdate()
    {
        if (HasAuthority)
        {
            DriveLocal();
            AnimateWheelVisuals();
        }
    }

    // Remote cars: animated every rendered frame from how the car actually moved on screen
    // (it's moved by sync smoothing in Update, so FixedUpdate -- which can run 0 or several
    // times per frame -- would mis-measure it, especially on slower PCs).
    private void LateUpdate()
    {
        if (!HasAuthority) AnimateRemoteWheels();
    }

    private void DriveLocal()
    {
        if (Keyboard.current == null) return;

        float accel = 0f;
        if (Keyboard.current.wKey.isPressed || Keyboard.current.upArrowKey.isPressed) accel = 1f;
        else if (Keyboard.current.sKey.isPressed || Keyboard.current.downArrowKey.isPressed) accel = -1f;

        float steer = 0f;
        if (Keyboard.current.aKey.isPressed || Keyboard.current.leftArrowKey.isPressed) steer = -1f;
        else if (Keyboard.current.dKey.isPressed || Keyboard.current.rightArrowKey.isPressed) steer = 1f;

        bool handbrake = Keyboard.current.spaceKey.isPressed;

        float torque = accel * motorTorque;
        float brake = handbrake ? brakeTorque : 0f;
        float steerAngle = steer * maxSteerAngle;

        if (rearLeft != null) { rearLeft.motorTorque = torque; rearLeft.brakeTorque = brake; }
        if (rearRight != null) { rearRight.motorTorque = torque; rearRight.brakeTorque = brake; }
        if (frontLeft != null) { frontLeft.steerAngle = steerAngle; frontLeft.brakeTorque = brake; }
        if (frontRight != null) { frontRight.steerAngle = steerAngle; frontRight.brakeTorque = brake; }
    }

    // WheelCollider is a purely physical component with no visual mesh of its own -- the
    // car's visible wheel meshes are separate child Transforms that have to be positioned/
    // rotated by hand every frame to track the (invisible) WheelColliders' actual simulated
    // pose. On a remote car the WheelColliders are disabled entirely (see Configure), so
    // there's no real per-wheel pose to read there -- visuals instead spin from an
    // approximated forward speed. This is a deliberate, disclosed simplification, not real
    // remote wheel simulation: it's enough for the spin to read as "moving," not an exact
    // match to what the driving player's own wheels are doing.
    //
    // Confirmed live (Racing tutorial): this used to read _rb.linearVelocity here, relying on
    // the CarVelocity (Rigidbody_Velocity) sync rule to keep it current on remote cars. That
    // never actually worked -- a remote car's Rigidbody is kinematic on purpose (see
    // Configure), and Unity refuses to let ANYTHING set linearVelocity on a kinematic body
    // (NetCrafterSyncBinding.ApplyIncoming now guards against the resulting error, but the
    // value still can't be applied there -- see that file for the general fix). A kinematic
    // body's own .linearVelocity also never reflects movement driven by directly assigning
    // transform.position/rotation the way Transform_Position/Rotation sync does, so even
    // fixing the error wouldn't have made this read anything meaningful. Approximating forward
    // speed from the position delta since last frame instead sidesteps the Rigidbody entirely
    // for this purpose -- it only ever needed *a* plausible speed number to drive the visual
    // spin rate, not the authoritative one.
    private void AnimateWheelVisuals()
    {
        if (HasAuthority)
        {
            ApplyWheelPose(frontLeft, frontLeftVisual);
            ApplyWheelPose(frontRight, frontRightVisual);
            ApplyWheelPose(rearLeft, rearLeftVisual);
            ApplyWheelPose(rearRight, rearRightVisual);
            return;
        }

    }

    // Remote wheels: spin from the distance travelled (forwards or backwards) at the real
    // wheel size, and steer the front wheels from how fast the car is turning. An
    // approximation -- the remote car has no wheel physics -- but it reads as driving.
    private void AnimateRemoteWheels()
    {
        float dt = Time.deltaTime;
        if (dt <= 0f) return;
        Vector3 pos = transform.position;
        float yaw = transform.eulerAngles.y;
        if (!_haveLastRemotePosition)
        {
            _lastRemotePosition = pos; _lastRemoteYaw = yaw; _haveLastRemotePosition = true;
            return;
        }
        Vector3 delta = pos - _lastRemotePosition;
        float yawDelta = Mathf.DeltaAngle(_lastRemoteYaw, yaw);
        _lastRemotePosition = pos; _lastRemoteYaw = yaw;
        if (delta.sqrMagnitude > 25f) return;   // a respawn/teleport, not driving

        float distance = Vector3.Dot(delta, transform.forward);   // signed: reversing spins backwards
        _visualSpinDegrees = Mathf.Repeat(_visualSpinDegrees + distance / _wheelRadius * Mathf.Rad2Deg, 360f);

        float speed = distance / dt;
        float targetSteer = 0f;
        if (Mathf.Abs(speed) > 0.5f)
        {
            float yawRate = yawDelta * Mathf.Deg2Rad / dt;   // rad/s
            targetSteer = Mathf.Atan(yawRate * _wheelbase / speed) * Mathf.Rad2Deg;
            targetSteer = Mathf.Clamp(targetSteer, -maxSteerAngle, maxSteerAngle);
        }
        _remoteSteer = Mathf.Lerp(_remoteSteer, targetSteer, 1f - Mathf.Exp(-10f * dt));

        Quaternion spin = Quaternion.Euler(_visualSpinDegrees, 0f, 0f);
        Quaternion steer = Quaternion.Euler(0f, _remoteSteer, 0f);
        if (frontLeftVisual != null) frontLeftVisual.localRotation = _flBase * steer * spin;
        if (frontRightVisual != null) frontRightVisual.localRotation = _frBase * steer * spin;
        if (rearLeftVisual != null) rearLeftVisual.localRotation = _rlBase * spin;
        if (rearRightVisual != null) rearRightVisual.localRotation = _rrBase * spin;
    }

    private static void ApplyWheelPose(WheelCollider collider, Transform visual)
    {
        if (collider == null || visual == null) return;
        collider.GetWorldPose(out Vector3 pos, out Quaternion rot);
        visual.SetPositionAndRotation(pos, rot);
    }

    // Not currently called anywhere (a hook for a future "reset on wrong-way/off-track"
    // feature) but public, so guard it the same way as NetCrafterSyncBinding.ApplyIncoming
    // regardless: only meaningful for the local player's own (non-kinematic) car -- a remote
    // car's position is driven by incoming sync, not this, and Unity rejects setting velocity
    // on a kinematic Rigidbody outright. Purely local either way, no networking here -- the
    // position change rides on this car's own already-continuous NetCrafterSyncBinding
    // updates, which every other client is already receiving.
    public void ResetToSpawn()
    {
        transform.SetPositionAndRotation(_spawnPosition, _spawnRotation);
        if (_rb != null && !_rb.isKinematic)
        {
            _rb.linearVelocity = Vector3.zero;
            _rb.angularVelocity = Vector3.zero;
        }
    }
}
}

Input System — no Input Actions asset needed. CarController reads keyboard input directly via Keyboard.current from Unity's new Input System, guarded for null per this package's own coding conventions. No Input Actions asset or Player Input component is required. If you see an error about the Input class switching, confirm Active Input Handling is set to Input System Package or Both (see Prerequisites).

Setup steps:

  1. Select LocalCar's root GameObject.
  2. Add Component → search for Car Controller → add it.
  3. Drag the four WheelCollider components into Front Left / Front Right / Rear Left / Rear Right.
  4. If the car has separate visual wheel mesh Transforms (distinct from the WheelColliders themselves), drag those into the matching Wheel Visual fields — optional, only used to spin/steer the wheels visually; leave blank and the car still drives correctly, it just won't show wheel rotation.

CarController.Configure(playerId, hasAuthority) isn't called yet — that happens once login is wired up in Part 7.6. For now, in Play mode with no RacingDemoController in the scene at all, HasAuthority defaults to false and the car won't respond to input; that's expected at this stage, not a bug. If you want to test raw driving feel right now before wiring up anything else, temporarily call GetComponent<CarController>().Configure(0, true) from any script's Start(), test, then remove it — Part 7 replaces this properly.

1.6 Follow Camera

Assets/PivecLabs/Examples/RacingDemo/Scripts/CarCamera.cs ships with the package — nothing to create here, this is what it contains:

Show CarCamera.csships with the package — nothing to type
C#
using UnityEngine;

namespace PivecLabs.NetCrafterRelay.Examples.RacingDemo
{
    // Smooth third-person follow camera. No networking dependency at all -- RacingDemoController
    // assigns Target to the local player's car once it's spawned (Part 7.6), and this script
    // never needs to know or care whether that car is local or remote.
    public class CarCamera : MonoBehaviour
    {
        public Transform target;
        public Vector3 offset = new(0f, 4f, -9f);
        public float smoothTime = 0.18f;

        private Vector3 _velocity;

        private void LateUpdate()
        {
            if (target == null) return;

            Vector3 desiredPosition = target.position + target.TransformDirection(offset);
            transform.position = Vector3.SmoothDamp(transform.position, desiredPosition, ref _velocity, smoothTime);

            Quaternion desiredRotation = Quaternion.LookRotation(target.position - transform.position + Vector3.up, Vector3.up);
            transform.rotation = Quaternion.Slerp(transform.rotation, desiredRotation, 1f - Mathf.Exp(-8f * Time.deltaTime));
        }
    }
}
  1. Select your Main Camera.
  2. Add Component → search for Car Camera → add it.
  3. Target: assign LocalCar's Transform (for now — Part 7.6 reassigns this automatically once a real local car is spawned after login).
  4. Leave Offset and Smooth Time at their defaults, or adjust to taste.

1.7 Test single-player driving

Temporarily call Configure(0, true) as described in 1.5, press Play, and confirm:

  • W / Up arrow: accelerate
  • S / Down arrow: brake/reverse
  • A/D or Left/Right arrows: steer
  • Space: handbrake

Adjust motorTorque (default 1500) and maxSteerAngle (default 30) on CarController if the handling feels too aggressive or too sluggish. Remove the temporary Configure() call before continuing — Part 7 wires this up for real.

Everything above this line is completely relay-agnostic — if you already have a working single-player driving setup, 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 Racing, click Create.

04

Part 3 — Define the messages#

Open the Gameplay Messages tab. Create the following.

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). colorIndex picks this player's car colour (Part 3's CarColorManager, 8 colours); spawnIndex picks which spawn point their car starts at — both computed host-side in Part 4, not sent by 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 and broadcasts this message to everyone else (Part 7.6). If the host itself disconnects, there's no one left to broadcast anything: each remaining joiner detects that independently, locally, without a PlayerLeft message at all — see the warning in Part 7.6.

3.4 RequestLapCompleted — a client's own car crossed the finish line

FieldValue
Message NameRequestLapCompleted
DirectionClientToHost
TransportReliable
Host Handler NameHandleLapCompleted

No fields — the host already knows who sent it (see Part 4).

3.5 LapCompleted — host's authoritative lap result, broadcast to everyone

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

Add four fields: playerId (int), lapNumber (int), lapTimeSeconds (float), totalTimeSeconds (float).

Same lesson as Chat/Co-op/Character: there's no message here for a car's continuous position or rotation. Those replicate through the sync system (Part 6), not the schema/message system — the five messages above only ever fire once each per event (login, join, leave, lap-request, lap-result), never on a per-frame cadence.

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 (roster-replay pattern shared with Co-op/Character's HandleLogin — see either tutorial for the full explanation of why the replay loop exists — plus Racing-specific colour/spawn assignment):

C#
string displayName = trigger.displayName;
int colorIndex = senderId % 8;
int spawnIndex = senderId % 4;   // fallback if all 4 slots are taken
var takenSpawns = new System.Collections.Generic.HashSet<int>();
foreach (var p in RacingGameState.Players.Values) takenSpawns.Add(p.spawnIndex);
for (int s = 0; s < 4; s++) { if (!takenSpawns.Contains(s)) { spawnIndex = s; break; } }

foreach (var kv in RacingGameState.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);
}

RacingGameState.Players[senderId] = new RacingGameState.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 spawns a remote instance for a newly-joined player.
RacingDemoController.Instance?.HostRegisterPlayerLocally(senderId, displayName, colorIndex, spawnIndex);

colorIndex/spawnIndex are computed here, host-side, from senderId — deterministic and never trusted from the client. This mirrors the same "always use the authoritative sender id, never trust a client-sent one" rule this package has followed since its very first (SFS3-era) handler generation — the reasoning hasn't changed even though nothing about how it's enforced is SFS3-specific anymore.

4.2 HandleLapCompleted

FieldValue
Handler NameHandleLapCompleted
Trigger MessageRequestLapCompleted
Response EventLapCompleted
Logic TypeCustom

Custom Host Code:

C#
if (RacingGameState.TryRecordLap(senderId, out int lapNumber, out float lapTimeSeconds, out float totalTimeSeconds))
{
    var ev = new LapCompletedEvent {
        playerId = senderId, lapNumber = lapNumber,
        lapTimeSeconds = lapTimeSeconds, totalTimeSeconds = totalTimeSeconds
    };
    connection.BroadcastToAll("LapCompleted", ev.Serialize(), true);

    // Same reasoning as HandleLogin above -- the host never receives its own broadcast.
    RacingDemoController.Instance?.HostRegisterLapLocally(senderId, lapNumber, lapTimeSeconds, totalTimeSeconds);
}

Why this is host-authoritative, and what it actually validates. The host doesn't simulate every car's physics itself — this is a relay, not a physics-authoritative server, so it has no way to verify a lap was actually driven honestly. What it can do, and what RacingGameState.TryRecordLap does, is refuse to count a lap that arrives implausibly soon after that same player's previous one (a MinLapSeconds floor, 5f by default) — not a perfect anti-cheat, but it does mean the single source of truth for "how many laps has player X completed" is the host's own count, broadcast to everyone, rather than each client trusting its own (or worse, another client's) locally-detected checkpoint crossing. Every client, including the one whose car actually crossed the line, updates its lap display from the LapCompleted broadcast — never directly from its own LapCheckpoint trigger. See Part 7.3.

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/Racing/Generated/:

  • Client/LoginRequest.cs, Client/PlayerJoinedEvent.cs, Client/PlayerLeftEvent.cs, Client/RequestLapCompletedRequest.cs, Client/LapCompletedEvent.cs, Client/RelayConnectionManager.cs
  • Host/HostActionRouter.cs
  • Config/RelayConfig.json

Let Unity recompile and check the Console for CS0103: The name 'RacingGameState' does not exist or CS0103: The name 'RacingDemoController' does not exist — if you see either, double-check Part 6.1's file exists (below).

6.1 The shared game-state helper

Assets/PivecLabs/Examples/RacingDemo/Scripts/RacingGameState.cs ships with the package — nothing to create here, this is what it contains:

Show RacingGameState.csships with the package — nothing to type
C#
using System.Collections.Generic;
using UnityEngine;

namespace PivecLabs.NetCrafterRelay.Examples.RacingDemo
{
    // Shared host-side race state -- who's connected (with their assigned colour/spawn slot) and
    // each player's lap progress. Kept outside Assets/PivecLabs/NetCrafterRelay/ so it compiles
    // into Assembly-CSharp alongside the generated Racing types, same reasoning as Chat's
    // ChatPlayerRegistry / Coop's CoopGameState / Character's CharacterGameState.
    public static class RacingGameState
    {
        public class PlayerInfo
        {
            public string displayName;
            public int colorIndex;
            public int spawnIndex;
        }

        public static readonly Dictionary<int, PlayerInfo> Players = new();

        private static readonly Dictionary<int, int> _lapCounts = new();
        private static readonly Dictionary<int, float> _lastLapTime = new();
        private static float _raceStartTime;
        // 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() { Reset(); }

        // Minimum real-world time a lap can take. The host is authoritative for WHEN a lap is
        // accepted and counted, but it doesn't simulate every car's physics itself (this is a
        // relay, not a physics-authoritative server) -- it can't verify a lap was actually driven.
        // This guard is the one thing it CAN meaningfully check without doing that: reject a
        // RequestLapCompleted that arrives far faster than a car could plausibly complete a real
        // circuit, the same "host is the single arbiter" shape as Co-op's TryCollectPickup dedup
        // check, just guarding against an implausibly-fast repeat instead of an exact duplicate.
        private const float MinLapSeconds = 5f;

        // Called from RacingDemoController.Awake() -- static state survives across repeated Unity
        // Editor Play-mode sessions when Domain Reload is disabled.
        public static void Reset()
        {
            Players.Clear();
            _lapCounts.Clear();
            _lastLapTime.Clear();
            _raceStartTime = Time.unscaledTime;
        }

        // Host-only. Returns false (and leaves lapNumber/lapTimeSeconds/totalTimeSeconds at their
        // computed-but-rejected values) if this lap arrived too soon after the player's previous one
        // to be plausible -- the caller should simply not broadcast anything in that case.
        public static bool TryRecordLap(int playerId, out int lapNumber, out float lapTimeSeconds, out float totalTimeSeconds)
        {
            float now = Time.unscaledTime;
            float last = _lastLapTime.TryGetValue(playerId, out float storedLast) ? storedLast : _raceStartTime;

            lapTimeSeconds = now - last;
            totalTimeSeconds = now - _raceStartTime;
            lapNumber = _lapCounts.TryGetValue(playerId, out int count) ? count : 0;

            if (lapTimeSeconds < MinLapSeconds)
                return false;

            lapNumber = count + 1;
            _lapCounts[playerId] = lapNumber;
            _lastLapTime[playerId] = now;
            return true;
        }
    }
}

Keep this file outside Assets/PivecLabs/NetCrafterRelay/ — same assembly-isolation reasoning as ChatPlayerRegistry/CoopGameState/CharacterGameState. If you're building multiple tutorials in the same project, RacingGameState doesn't collide with any of them — all four are distinctly named plain static classes compiling into the same Assembly-CSharp assembly.

07

Part 6 — Create the two 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/RacingDemo/ via right-click → Create → PivecLabs → NetCrafterRelay → Sync Rule.

Asset nameRule NameSync TargetSync Mode
CarPositionSyncRuleCarPositionTransform_PositionOnChange
CarRotationSyncRuleCarRotationTransform_RotationOnChange

Create and rename one row at a time — don't create both, 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 and Unity silently appends " 1", " 2" to keep filenames unique (SyncRule 1.asset) — the risk is smaller with only two rules than Character's six, but the mechanism (and the fix, if you already have one: select it, press F2, retype the correct name) is identical.

These two rules directly move a remote car. Since 2.0 the remote car glides toward each received Transform_Position/Transform_Rotation (Smooth Remote Motion on the Sync Binding, see the Manual's Remote smoothing). Nothing else needs to be synced: the remote wheels' spin and steering (Part 1.5) are worked out locally from how the car moves between frames, not driven by any additional sync rule.

You'll assign these two rules to two NetCrafterSyncBinding components in Part 7 — one set on the local car, another matching set on the remote car prefab.

08

Part 7 — Build the scene#

7.1 Add sync bindings to the local car

Select LocalCar's root GameObject (from Part 1.4) in your scene. Twice: Add Component → NetCrafter → Sync Binding, then immediately drag one of Part 6's two rule assets onto that specific binding's Rule field before adding the next one.

Leave every added Sync Binding component's checkbox unchecked — RacingDemoController (Part 7.6) enables all of them together, with the correct objectId/authority, right after login.

Leave Has Authority unchecked and Object Id at 0 on both of these components — don't set them here, for either the local car or (in Part 7.2) the remote prefab. These are visible, editable Inspector fields, but they're only ever meant to be set by Configure(id, authority) at runtime, once login actually confirms this client's real player id and whether it's the host. Setting them by hand risks a one-time setup step (OnEnable() — subscribing to incoming sync, among other things) locking in against the wrong value before Configure() ever runs, since Configure() updates the fields but doesn't re-run that setup — see the Character tutorial's Part 7.1 for the full mechanism if you want the details. Leaving the checkbox unchecked (as instructed above) is what prevents this from ever mattering.

7.2 Build the remote car prefab

Step 1 — Duplicate, unpack, and check. Right-click LocalCar in the Hierarchy → Duplicate. Rename the duplicate RemoteCarPrefab. If you didn't already unpack the original car prefab back in Part 1.4, right-click RemoteCarPrefab → Prefab → Unpack Completely now, before touching any components.

Don't skip the unpack — this is a real, confirmed trap, not a defensive formality (see the Character tutorial's Part 7.2 for the full mechanism: 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). Unpacking severs that link immediately, before it can happen.

Both NetCrafterSyncBinding components already exist on RemoteCarPrefab — they were duplicated along with everything else in Step 1, rules and all. Leave both of them unchecked, same as the local car — RacingDemoController configures and enables both the moment this prefab is spawned for an actual remote player (Part 7.6).

Step 2 — Disable local-only components. CarController stays on RemoteCarPrefab (it drives BOTH local and remote behavior internally, gated on HasAuthority — see Part 1.5's source), but nothing else needs to change here: Configure(playerId, false) (called at spawn time, Part 7.6) is what actually disables the Rigidbody's physics and the WheelColliders for a remote instance, not a manual component removal step. There's nothing else on the car that reads local input.

Why there's no Rigidbody_Velocity sync rule here. Configure(playerId, false) sets the remote car's Rigidbody isKinematic = true and its Interpolate to None — correct and necessary, so its own local physics can't fight the direct position/rotation writes (with interpolation left on, Unity pulls the car back toward the physics pose every frame: measured, a 10 m move came out as 3.5 m) Transform_Position/Transform_Rotation sync apply every update (same reasoning as the root-motion note in the Character tutorial). A kinematic Rigidbody's own .linearVelocity never reflects movement driven by directly assigning transform.position the way this sync does, so a velocity-based sync rule has nothing meaningful to read on a remote car regardless. The remote wheels (Part 1.5) spin for the distance the car moves each frame, at the real wheel size, and the front wheels steer from how fast the car turns — no Rigidbody read involved, and no third sync rule needed to support it. (An earlier revision of this tutorial did ship a CarVelocity/Rigidbody_Velocity rule anyway, purely as an unused artifact of an earlier wheel-spin approach — removed once confirmed nothing consumed it; see the Changelog if you're curious.)

Step 3 — Save and remove from the Hierarchy. Drag RemoteCarPrefab from the Hierarchy into Assets/PivecLabs/Examples/RacingDemo/Prefabs/RemoteCarPrefab.prefab, then delete it from the Hierarchy — it's now a prefab asset, spawned at runtime instead of pre-placed.

7.3 Place the lap checkpoint

Assets/PivecLabs/Examples/RacingDemo/Scripts/LapCheckpoint.cs ships with the package — nothing to create here, this is what it contains:

Show LapCheckpoint.csships with the package — nothing to type
C#
using UnityEngine;

namespace PivecLabs.NetCrafterRelay.Examples.RacingDemo
{
    // Trigger volume placed at the track's start/finish line (Part 7.3). Every client's own
    // car passing through fires a lap-completion REQUEST to the host, not a lap completion
    // directly -- the host is the single authority on whether a lap actually counts (see
    // RacingGameState.TryRecordLap), the same host-authoritative shape as Co-op's pickups. A
    // remote car's collider passing through this trigger is ignored entirely: only report the
    // LOCAL player's own crossing, since that's the only one this client can meaningfully act
    // on, and every client (host included) already gets every player's official lap count back
    // via the broadcast "LapCompleted" event regardless of who crossed which checkpoint.
    [RequireComponent(typeof(Collider))]
    public class LapCheckpoint : MonoBehaviour
    {
        private void OnTriggerEnter(Collider other)
        {
            var car = other.GetComponentInParent<CarController>();
            if (car == null || !car.HasAuthority) return;

            RacingDemoController.Instance?.RequestLapCompleted();
        }
    }
}
  1. At your track's start/finish line (the exact spot you noted in Part 1.1), Create Empty — name it LapCheckpoint.
  2. Add Component → Box Collider. Size and position it to span the full width of the track at the finish line, thin along the direction of travel (a car should pass through it in one frame at racing speed, not sit inside it). Check Is Trigger.
  3. Add Component → search for Lap Checkpoint → add it.

If your track package didn't ship an obvious finish-line marker to align this against, the start/finish line is wherever you decide it is — place LapCheckpoint anywhere on the track's own road surface, spanning its width, and treat that as the finish line for spawn-point placement (Part 7.6) too, so cars start facing the direction they'll complete a lap in.

7.4 Build the UI

  1. Canvas (Screen Space - Overlay) — name it UICanvas.
  2. LoginPanel: TMP Text (Title, "Racing"), TMP Input Field (DisplayNameInput, placeholder "Enter your name..."), TMP Button (ContinueButton, "Continue").
  3. LobbyPanel (unchecked by default): TMP Button (HostButton, "Host Game"), TMP Input Field (JoinCodeInput, placeholder "Join code..."), TMP Button (JoinButton, "Join Game"), TMP Text (JoinCodeDisplay, blank), TMP Text (StatusText, blank — shows connection errors/retry status; kept separate from JoinCodeDisplay so success and error text never share one field).
  4. GameplayPanel (unchecked by default, Image alpha 0 — gameplay is the 3D track behind it): TMP Text (LeaderboardText, blank, anchored top-left) — sorted lap count / time, refreshed on every LapCompleted and player join/leave.

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

Open Scenes → Prefab Generator in the NetCrafter Relay window, confirm Racing is the selected schema, click Create RelayConnectionManager Prefab. This writes RelayConnectionManager.prefab to Definitions/Racing/Prefabs/ (a sibling of Generated/, not inside it — this prefab holds your actual relay settings once configured, so it's never touched by code regeneration) — do this before the Scene Assistant step below, so the connection-manager GameObject it adds to the scene comes from this prefab rather than a raw, disconnected GameObject. (Scene Assistant falls back to creating one either way if you skip this — nothing breaks — but building from the prefab is the intended path and keeps the scene object linked to a reusable asset.)

Open Scenes → Scene Assistant, confirm Racing is still the selected schema, confirm Add Event Dispatcher is checked, click Add to Existing Scene. This adds:

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

Why the RelayConnectionManager GameObject starts disabled. Its Start() calls Connect() unconditionally, and Connect() defaults to hosting a new session when no join code is pending — active from the instant the scene loads, it would start hosting immediately, before Login has even been looked at. Scene Assistant creates it pre-disabled specifically so this can't happen; RacingDemoController.Awake() (below) also forces it inactive defensively on top of that, the same belt-and-suspenders pattern every other tutorial in this package uses.

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

7.6 Attach and wire RacingDemoController

Assets/PivecLabs/Examples/RacingDemo/Scripts/RacingDemoController.cs ships with the package — nothing to create here, this is what it contains:

Show RacingDemoController.csships with the package — nothing to type
C#
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using TMPro;
using PivecLabs.Generated.Racing;
using PivecLabs.NetCrafterRelay;

namespace PivecLabs.NetCrafterRelay.Examples.RacingDemo
{

// Reference implementation backing the "NetCrafter Relay — Multiplayer Racing" tutorial.
// Host-relay-only, same as every other schema: joiners never talk to each other directly,
// only through the host. Buttons are wired via the Inspector (Button -> On Click ()), not
// AddListener in code -- see the tutorial doc for the exact wiring steps. PlayerJoined/
// PlayerLeft/LapCompleted are likewise wired via the Inspector through
// NetCrafterSceneEventRouter bindings (Settings -> Scene Events), not code-based
// NetCrafterEventDispatcher.Subscribe calls -- that mechanism exists specifically for
// schema-defined events. RelayHosting/ConnectionLost/RelayStatus stay code-subscribed
// because they're framework-level notifications, not schema events.
public class RacingDemoController : MonoBehaviour
{
    // Referenced by HandleLogin/HandleLapCompleted'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 RacingDemoController 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;
    // Optional. Shows connection errors and transient retry status on the Lobby panel where
    // a player can actually see them, instead of console-only -- same pattern established
    // for Chat/Coop/Character. Kept separate from joinCodeDisplay so a success message and
    // an error/retry message can never occupy the same field at once.
    public TMP_Text statusText;

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

    [Header("Cars and track")]
    public GameObject localCar;
    public GameObject remoteCarPrefab;
    public Transform[] spawnPoints;
    public CarCamera carCamera;

    private RelayConnectionManager relay;
    private string displayName = "Player";
    private NetCrafterSyncBinding[] _localBindings;
    private CarController _localCarController;
    private CarColorManager _localCarColorManager;
    private readonly Dictionary<int, GameObject> _remoteCars = new();

    // Client-side display copy of lap progress -- updated from every LapCompleted broadcast
    // this client receives, regardless of host/joiner. RacingGameState's own lap-count
    // tracking is the HOST's authoritative copy used for validation (TryRecordLap's minimum
    // -lap-time guard), not for UI on every client -- same split as Co-op's _scores vs.
    // CoopGameState.TryCollectPickup.
    private readonly Dictionary<int, (int lapNumber, float lapTimeSeconds, float totalTimeSeconds)> _lapProgress = new();

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

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

        _localBindings = localCar.GetComponents<NetCrafterSyncBinding>();
        _localCarController = localCar.GetComponent<CarController>();
        _localCarColorManager = localCar.GetComponent<CarColorManager>();

        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 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); }
    private void ShowGameplay() { loginPanel.SetActive(false); lobbyPanel.SetActive(false); gameplayPanel.SetActive(true); ShowHudJoinCode(true); }

    public void OnLoginClicked()
    {
        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("[RacingDemo] 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($"[RacingDemo] Failed to connect within {ConnectTimeoutSeconds}s."); yield break; }

        if (relay.IsHost)
        {
            int colorIndex = relay.LocalUserId % 8;
            int spawnIndex = relay.LocalUserId % Mathf.Max(1, spawnPoints.Length);
            RacingGameState.Players[relay.LocalUserId] = new RacingGameState.PlayerInfo
            {
                displayName = displayName, colorIndex = colorIndex, spawnIndex = spawnIndex
            };
            relay.OnPeerDisconnected += OnHostDetectedPeerDisconnected;
            yield return new WaitForSeconds(HostLobbyDisplaySeconds);
        }
        else
        {
            // Confirmed live: without this, a joiner never learns the host itself has
            // disconnected -- only the host side of this event was wired (below), so a
            // departed host's own remote car sat frozen forever on every remaining client.
            // See OnJoinerDetectedHostDisconnected for why this is symmetric with
            // OnHostDetectedPeerDisconnected despite there being no BroadcastToAll here.
            relay.OnPeerDisconnected += OnJoinerDetectedHostDisconnected;
            new LoginRequest { displayName = displayName }.Send(relay);
        }

        ConfigureLocalPlayer();
        RefreshLeaderboard();
        ShowGameplay();
    }

    private void ConfigureLocalPlayer()
    {
        int myId = relay.LocalUserId;
        foreach (var binding in _localBindings)
        {
            binding.Configure(myId, true);
            binding.enabled = true;
        }

        _localCarController?.Configure(myId, true);

        if (RacingGameState.Players.TryGetValue(myId, out var info))
        {
            _localCarColorManager?.SetColor(info.colorIndex);
            if (spawnPoints != null && info.spawnIndex >= 0 && info.spawnIndex < spawnPoints.Length)
                TeleportLocalCar(spawnPoints[info.spawnIndex].position, spawnPoints[info.spawnIndex].rotation);
        }

        if (carCamera != null) carCamera.target = localCar.transform;
    }

    // The local car's Rigidbody uses interpolation, which re-applies the physics pose to the
    // Transform every frame: moving only the Transform was undone, and the car stayed where it was
    // (confirmed in NetCrafter Pro's identical Racing demo). Move the body, the Transform and the
    // physics scene together, and stop any motion it had.
    private void TeleportLocalCar(Vector3 position, Quaternion rotation)
    {
        var rb = localCar.GetComponent<Rigidbody>();
        if (rb != null)
        {
            if (!rb.isKinematic)
            {
                rb.linearVelocity = Vector3.zero;
                rb.angularVelocity = Vector3.zero;
            }
            rb.position = position;
            rb.rotation = rotation;
        }
        localCar.transform.SetPositionAndRotation(position, rotation);
        Physics.SyncTransforms();
    }

    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. Confirmed live
    // (Racing tutorial): a departed HOST's own remote car was never cleaned up on
    // remaining joiners, because only the host branch of SendLoginWhenConnected ever
    // subscribed to relay.OnPeerDisconnected -- a joiner never learned its one and only
    // peer (the host) had gone quiet. RelayConnectionManager always fires this with
    // peerId 0 for a joiner ("its only peer is always the host"), which lines up exactly
    // with the host's own RacingGameState.Players/relay.LocalUserId key of 0 (see
    // RelayConnectionManager's HostSession -- localUserId = 0 there unconditionally), so
    // OnPlayerLeftReceived(0) here destroys and untracks the same frozen car the host-side
    // path would have if it were still alive to broadcast PlayerLeft. There's nothing to
    // BroadcastToAll here, unlike the host-side handler above -- 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. Also surfaces a status message: unlike an ordinary player
    // leaving, this is the whole session ending for this client, not just one fewer racer.
    private void OnJoinerDetectedHostDisconnected(int peerId)
    {
        OnPlayerLeftReceived(peerId);
        if (statusText != null) statusText.text = "Host disconnected — connection lost.";
    }

    // Wired to the PlayerJoined binding's "On Received" UnityEvent in the Scene Events tab.
    public void OnPlayerJoinedReceived()
    {
        var ev = (PlayerJoinedEvent)NetCrafterSceneEventRouter.Instance.GetLastPayload("PlayerJoined");
        RacingGameState.Players[ev.playerId] = new RacingGameState.PlayerInfo
        {
            displayName = ev.displayName, colorIndex = ev.colorIndex, spawnIndex = ev.spawnIndex
        };

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

        RefreshLeaderboard();
    }

    // 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("PlayerJoined", ...) tells every OTHER connected peer to spawn a
    // remote instance for the new joiner, but the host that BROADCASTS it never receives
    // its own broadcast as an incoming wire event -- so without this direct call, the
    // host's own OnPlayerJoinedReceived() would simply never fire for anyone, and the host
    // would never see remote cars for its own joiners (same lesson as Chat/Character).
    public void HostRegisterPlayerLocally(int playerId, string displayNameForPlayer, int colorIndex, int spawnIndex)
    {
        RacingGameState.Players[playerId] = new RacingGameState.PlayerInfo
        {
            displayName = displayNameForPlayer, colorIndex = colorIndex, spawnIndex = spawnIndex
        };
        if (playerId != relay.LocalUserId)
            SpawnOrUpdateRemote(playerId, displayNameForPlayer, colorIndex, spawnIndex);
        RefreshLeaderboard();
    }

    private void SpawnOrUpdateRemote(int playerId, string displayNameForRemote, int colorIndex, int spawnIndex)
    {
        if (_remoteCars.TryGetValue(playerId, out var existing))
        {
            existing.GetComponent<CarColorManager>()?.SetColor(colorIndex);
            return;
        }

        var instance = Instantiate(remoteCarPrefab);
        if (spawnPoints != null && spawnIndex >= 0 && spawnIndex < spawnPoints.Length)
            instance.transform.SetPositionAndRotation(
                spawnPoints[spawnIndex].position, spawnPoints[spawnIndex].rotation);

        foreach (var binding in instance.GetComponents<NetCrafterSyncBinding>())
        {
            binding.Configure(playerId, false);
            binding.enabled = true;
        }

        instance.GetComponent<CarController>()?.Configure(playerId, false);
        instance.GetComponent<CarColorManager>()?.SetColor(colorIndex);

        _remoteCars[playerId] = instance;
    }

    public void OnPlayerLeftReceived(int playerId)
    {
        RacingGameState.Players.Remove(playerId);
        _lapProgress.Remove(playerId);
        if (_remoteCars.TryGetValue(playerId, out var instance))
        {
            Destroy(instance);
            _remoteCars.Remove(playerId);
        }
        RefreshLeaderboard();
    }

    // Wired to the PlayerLeft binding's "On Received" UnityEvent in the Scene Events tab.
    public void OnPlayerLeftBroadcastReceived()
    {
        var ev = (PlayerLeftEvent)NetCrafterSceneEventRouter.Instance.GetLastPayload("PlayerLeft");
        OnPlayerLeftReceived(ev.playerId);
    }

    // Called by LapCheckpoint's trigger for the LOCAL player's own car only. Host-
    // authoritative, same "host can't Send() to itself" lesson as every other tutorial's
    // host-originated action: the host validates and broadcasts directly instead of routing
    // a message to itself that would never actually be sent.
    public void RequestLapCompleted()
    {
        if (relay.IsHost)
        {
            if (RacingGameState.TryRecordLap(relay.LocalUserId, out int lapNumber, out float lapTimeSeconds, out float totalTimeSeconds))
            {
                var ev = new LapCompletedEvent
                {
                    playerId = relay.LocalUserId, lapNumber = lapNumber,
                    lapTimeSeconds = lapTimeSeconds, totalTimeSeconds = totalTimeSeconds
                };
                relay.BroadcastToAll("LapCompleted", ev.Serialize(), true);
                OnLapCompletedReceivedInternal(ev);
            }
        }
        else
        {
            new RequestLapCompletedRequest().Send(relay);
        }
    }

    // Wired to the LapCompleted binding's "On Received" UnityEvent in the Scene Events tab.
    public void OnLapCompletedReceived()
    {
        var ev = (LapCompletedEvent)NetCrafterSceneEventRouter.Instance.GetLastPayload("LapCompleted");
        OnLapCompletedReceivedInternal(ev);
    }

    // Called directly from HandleLapCompleted's Custom Host Code -- same "host never
    // receives its own broadcast" reasoning as HostRegisterPlayerLocally above.
    public void HostRegisterLapLocally(int playerId, int lapNumber, float lapTimeSeconds, float totalTimeSeconds)
    {
        OnLapCompletedReceivedInternal(new LapCompletedEvent
        {
            playerId = playerId, lapNumber = lapNumber,
            lapTimeSeconds = lapTimeSeconds, totalTimeSeconds = totalTimeSeconds
        });
    }

    private void OnLapCompletedReceivedInternal(LapCompletedEvent ev)
    {
        _lapProgress[ev.playerId] = (ev.lapNumber, ev.lapTimeSeconds, ev.totalTimeSeconds);
        RefreshLeaderboard();
    }

    // Sorted by lap count (descending), then total time (ascending) within the same lap --
    // furthest-along, then fastest. Players with no recorded lap yet still appear, at 0
    // laps, so the leaderboard always lists everyone connected, not just current leaders.
    private void RefreshLeaderboard()
    {
        var rows = new List<(string name, int laps, float totalTime)>();
        foreach (var kv in RacingGameState.Players)
        {
            _lapProgress.TryGetValue(kv.Key, out var progress);
            rows.Add((kv.Value.displayName, progress.lapNumber, progress.totalTimeSeconds));
        }

        rows.Sort((a, b) => b.laps != a.laps ? b.laps.CompareTo(a.laps) : a.totalTime.CompareTo(b.totalTime));

        var sb = new StringBuilder();
        for (int i = 0; i < rows.Count; i++)
            sb.AppendLine($"{i + 1}. {rows[i].name} — Lap {rows[i].laps} ({rows[i].totalTime:0.0}s)");

        if (leaderboardText != null) leaderboardText.text = sb.ToString();
    }
}
}

Wire it up:

  1. Create an empty GameObject named RacingDemoController, drag the script onto it.
  2. Wire:
FieldDrag in
Relay Connection Manager Objectthe RelayConnectionManager GameObject
Login PanelLoginPanel
Display Name InputDisplayNameInput
Lobby PanelLobbyPanel
Join Code InputJoinCodeInput
Join Code DisplayJoinCodeDisplay
Status TextStatusText — optional; leave unassigned and this feature is silently skipped
Gameplay PanelGameplayPanel
Leaderboard TextLeaderboardText
Local CarLocalCar (Part 1.4)
Remote Car PrefabRemoteCarPrefab.prefab (Part 7.2)
Spawn Points (size 4)four empty GameObjects placed around your track's start line, near LapCheckpoint (Part 7.3), each facing the direction of travel — this array's index is the network player id % 4 each spawn point maps to (Part 4.1)
Car Camerayour Main Camera's CarCamera component (Part 1.6)
  1. Wire the buttons and events:
    • ContinueButton → On Click () → RacingDemoController.OnLoginClicked()
    • HostButton → On Click () → RacingDemoController.OnHostClicked()
    • JoinButton → On Click () → RacingDemoController.OnJoinClicked()
    • SceneEventRouter's PlayerJoined binding → On Received → RacingDemoController.OnPlayerJoinedReceived()
    • SceneEventRouter's PlayerLeft binding → On Received → RacingDemoController.OnPlayerLeftBroadcastReceived()
    • SceneEventRouter's LapCompleted binding → On Received → RacingDemoController.OnLapCompletedReceived()

Confirmed live: a departed player's car used to stay behind forever if the departing player was the HOST, not a joiner. Disconnect detection itself (RelayConnectionManager's OnPeerDisconnected, at once for a normal quit, since 2.0 sends a goodbye, or after ~15s of silence for a crash) already worked correctly either way. The gap was in who listens: SendLoginWhenConnected's host branch always subscribed to OnPeerDisconnected so the host could broadcast PlayerLeft and clean up a departed joiner's car everywhere — but nothing on the joiner side ever subscribed, so if the host disconnected, every remaining joiner just kept the host's now-frozen car sitting in their scene indefinitely, with no message coming to tell them otherwise. RacingDemoController.cs now also subscribes in the joiner branch: since a joiner's only peer is always the host, and the host is always assigned network id 0, OnPeerDisconnected firing there reuses the exact same OnPlayerLeftReceived(0) cleanup a PlayerLeft broadcast would have triggered — destroying the host's car and dropping it from the leaderboard — plus a StatusText message, since unlike an ordinary player leaving, this is the whole session ending for that client, not just one fewer racer. There's still no host migration or reconnection: once the host is gone, remaining joiners have no path back to the Lobby panel without restarting — a known, disclosed limitation, not something this fix attempts to solve.

09

Part 8 — Run it#

  1. Run one copy — the host. Enter a name, Continue, Host Game. The Lobby panel stays up with your join code for a few seconds before moving on to the track automatically. Drive a lap — confirm your own car handles exactly as in Part 1.7, and the leaderboard shows your name at "Lap 0" until you cross LapCheckpoint, then "Lap 1" with a time.
  2. Run 1–3 more copies — joiners. Enter a name, Continue, type in the join code, Join Game.
  3. On every client, confirm:
    • Every other connected player's car appears, correctly coloured (colorIndex), at its own spawn point.
    • Driving on any one client's own car shows smooth movement — not just a moved position, actual wheel spin — on every other client's screen.
    • Crossing LapCheckpoint updates the leaderboard identically on every client, including the one that crossed it, at the same lap number and time.
    • The leaderboard re-sorts as lap counts/times change.
  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 car disappears from every remaining client and the leaderboard 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 a "Host disconnected" message and the host's own now-frozen car disappears from their scene — independently on each joiner's client, since joiners never talk to each other directly (Part 7.6). There's no way to keep playing after this — no host migration — so this is as far as that session goes; host or join a fresh session to continue testing.

If hosting or joining fails outright — relay unreachable, join code not found — StatusText on the Lobby panel shows a plain-language message instead of a silent, unexplained Lobby screen (full detail still goes to the Console, unchanged). A join that's still retrying briefly shows "Retrying connection… (attempt N of 3)" first.

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) so anyone can read it out to a friend.

If cars move but the leaderboard never updates, check the Console for HandleLapCompleted logs on the host's copy — same troubleshooting instinct as every other tutorial's host-action debugging. If cars don't appear at all for a joiner, see Common Mistakes below before assuming the network itself is broken.

10

Common mistakes#

A remote car doesn't move at all. Check that both NetCrafterSyncBinding → Rule fields on RemoteCarPrefab are actually assigned (Part 7.1/7.2) — an unassigned rule self-disables with a Console warning ("No SyncRuleDefinition assigned... Disabling."), the same failure mode documented in the Co-op and Character tutorials.

Remote wheels don't spin, but the car itself moves correctly. Wheel spin and steering are worked out entirely from how the remote car moves between frames (Part 1.5) — there's no sync rule involved in wheel-spin at all, so this isn't a sync-binding wiring issue. Check that Wheel Visual fields are actually assigned on RemoteCarPrefab's CarController (Part 1.5) — if those are all left blank, there's nothing for the spin animation to apply to, and that reads identically to "wheels not spinning."

Track renders solid magenta/pink. Missing shader — the imported track's materials weren't converted for this project's render pipeline (URP). Run Window → Rendering → Render Pipeline Converter (or Edit → Render Pipeline → Universal Render Pipeline → Upgrade Project Materials on older Unity versions) — see Part 1.1.

Lap never counts even though the car clearly crossed the line. Two likely causes: (1) LapCheckpoint's Box Collider isn't actually set to Is Trigger, so OnTriggerEnter never fires at all; (2) you're testing laps faster than RacingGameState.MinLapSeconds (5f by default) apart — the host-authoritative guard in Part 4.2 is rejecting it as implausibly fast, not silently failing. Slow down, or lower MinLapSeconds in RacingGameState.cs for testing.

Joiners see each other's cars fine, but the host sees no one. Confirmed pattern from every other tutorial in this package — this is exactly 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 — the host has to be told about its own joiners directly. If you're seeing this, double-check RacingDemoController.Instance exists and HandleLogin's Custom Host Code ends with the HostRegisterPlayerLocally line.

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 building this one via Scene Assistant. Delete it and re-add via Scenes → Scene Assistant → Add to Existing Scene.

11

What's Next#

FeatureDescription
Race start/countdownGate LapCheckpoint (or car input) behind a host-broadcast "go" signal so laps can't start before everyone's ready
Best-lap trackingRacingGameState already computes lapTimeSeconds per lap — track a per-player minimum and surface it on the leaderboard
Position orderCompare every player's (lapNumber, totalTimeSeconds) — already computed — to show live 1st/2nd/3rd, not just a lap count
AI opponentsA non-networked car following a waypoint path, using the same CarController but never calling Configure() with real network authority
Power-upsA pickup trigger following Co-op's TryCollectPickup host-authoritative pattern directly

Tutorial by Pivec Labs — NetCrafter Relay