# Solo-First Multiplayer Rooms, Named Hubs & VR Avatars with CCGD.GameNet in Unity 6

> Browser-ready multiplayer in Unity 6 using CCGD.GameNet: solo-first host authority, 60 Hz interpolated avatars, named social rooms (JoinRoom/LeaveRoom), VR head-and-hand pose sync, cosmetic tags, and deterministic GameNet.Sim PlayMode tests.

- **Canonical page:** https://gamecrew.ai/techniques/unity/multiplayer-room-sync-and-vr-avatars
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Unity 6
- **Category:** gameplay
- **Tags:** `multiplayer`, `networking`, `rooms`, `lobby`, `co-op`, `avatars`, `interpolation`, `host-migration`, `named-rooms`, `vr`, `cosmetics`, `gamenet`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-30)
- **Demo:** No demo

## When to Use (and When Not To)

Use `CCGD.GameNet` (`#if CCGD_MP`) for every Unity 6 game declaring `"multiplayer"` in `game.json` — including co-op VR horror lobbies, arm-push tag arenas, party dodgeball brawlers, shared mountain lodges, and open-world city roleplay hubs.

Never install third-party networking SDKs (`com.unity.netcode.*`, Mirror, Photon, or raw WebSockets): the studio's play host already owns the WebSocket relay, 4-letter room codes, invite links, `@handle` identities, and named shared zones through `CCGD.GameNet`.

## Mathematical & Algorithmic Core

1. **Solo-First Host Authority**: When offline or alone in a room, `GameNet.IsHost` is `true` and `GameNet.Players` contains `[GameNet.Me]` at `SpawnIndex = 0`. Run ALL shared world state mutations (pickups, round timers, scores, enemy AI, shop transactions) behind `if (GameNet.IsHost)` and broadcast compact patches via `GameNet.SetState(...)`. Guests request actions with `GameNet.SendData("claim", payload, "host")`.
2. **Host Migration Without Reset**: Subscribe to `GameNet.HostChanged`. When Peer 1 disconnects, the lowest remaining peer ID automatically becomes host; it immediately resumes simulation from the existing `GameNet.StateJson` without restarting the scene.
3. **20 Hz Send / 60 Hz Avatar Interpolation**: Call `GameNet.SetMyPose(pos, yawDeg, anim, pitchDeg)` every frame; `GameNet` throttles deltas to 20 Hz and interpolates remote peers at 60 Hz via `GameNet.BindAvatar(...)` or `GameNet.TryGetPose(peer.Id, out pose)`.
4. **VR Head + Two-Hand Avatar Sync**: For VR multiplayer games, send quantized hand offsets relative to the avatar root (`[lx, ly, lz, rx, ry, rz]`) at 15 Hz via `GameNet.SendData("vr_hands", ...)` and spring-smooth remote left/right hand transforms on each bound avatar so teammates see waving, grabbing, and arm-pushing clearly.
5. **Named Social Zones (`JoinRoom` / `LeaveRoom`)**: For open worlds or mountain/mall hubs where players seamlessly meet at landmarks (e.g., `"lodge-summit"`, `"mall-atrium"`), call `GameNet.JoinRoom(zoneSlug, maxPlayers: 8)` when entering the trigger volume and `GameNet.LeaveRoom()` on exit.

## Engine Implementation

### Solo-First Co-Op Room & VR Hand Sync Controller (`Assets/Game/Runtime/Net/CoopRoomController.cs`)

```csharp
using System;
using System.Collections.Generic;
using UnityEngine;
#if CCGD_MP
using CCGD;
#endif

namespace Game.Net
{
    [Serializable]
    public struct ClaimPayload { public int index; }

    [Serializable]
    public struct VrHandsPayload
    {
        public float lx, ly, lz;
        public float rx, ry, rz;
        public string hatId;
    }

    public sealed class CoopRoomController : MonoBehaviour
    {
        public Transform LocalPlayer;
        public Transform AvatarsRoot;
        public Transform[] SpawnPoints;
        public GameObject[] SharedPickups;
        public string AutoJoinZoneRoom = ""; // optional named room e.g. "lodge-main"

        readonly HashSet<int> claimed = new HashSet<int>();
        readonly Dictionary<int, (Transform left, Transform right, Vector3 lTarget, Vector3 rTarget)> remoteHands =
            new Dictionary<int, (Transform, Transform, Vector3, Vector3)>();
        float handSendAccum;
        string localHatId = "none";

        void Start()
        {
#if CCGD_MP
            PlaceAtSpawnSlot(GameNet.SpawnIndex);
            GameNet.BindAvatar(AvatarsRoot, BuildPeerAvatar);
            GameNet.StateChanged += OnRoomStateChanged;
            GameNet.HostChanged += OnHostChanged;
            GameNet.PeerLeft += p => remoteHands.Remove(p.Id);
            GameNet.OnEvent("claim_pickup", OnClaimPickupRequest);
            GameNet.OnEvent("vr_hands", OnRemoteVrHands);

            if (!string.IsNullOrEmpty(AutoJoinZoneRoom))
                GameNet.JoinRoom(AutoJoinZoneRoom, maxPlayers: 8);

            if (GameNet.IsHost)
                PublishClaimedState();
#endif
        }

        void OnDestroy()
        {
#if CCGD_MP
            GameNet.StateChanged -= OnRoomStateChanged;
            GameNet.HostChanged -= OnHostChanged;
#endif
        }

        void Update()
        {
            float dt = Mathf.Min(Time.deltaTime, 0.05f);
#if CCGD_MP
            if (LocalPlayer != null)
            {
                GameNet.SetMyPose(
                    LocalPlayer.position,
                    LocalPlayer.eulerAngles.y,
                    "move",
                    0f);
            }

            // Smooth remote VR hand transforms at 60+ Hz.
            float blend = 1f - Mathf.Exp(-18f * dt);
            foreach (var kv in remoteHands)
            {
                if (kv.Value.left != null)
                    kv.Value.left.localPosition = Vector3.Lerp(kv.Value.left.localPosition, kv.Value.lTarget, blend);
                if (kv.Value.right != null)
                    kv.Value.right.localPosition = Vector3.Lerp(kv.Value.right.localPosition, kv.Value.rTarget, blend);
            }

#if CCGD_VR
            if (GameXR.Active && LocalPlayer != null)
            {
                handSendAccum += dt;
                if (handSendAccum >= 0.066f)
                {
                    handSendAccum = 0f;
                    var lh = GameXR.Hand("left");
                    var rh = GameXR.Hand("right");
                    Vector3 l = lh != null && lh.Grip != null ? LocalPlayer.InverseTransformPoint(lh.Grip.position) : new Vector3(-0.3f, 1.1f, 0.25f);
                    Vector3 r = rh != null && rh.Grip != null ? LocalPlayer.InverseTransformPoint(rh.Grip.position) : new Vector3(0.3f, 1.1f, 0.25f);
                    GameNet.SendData("vr_hands", new VrHandsPayload
                    {
                        lx = Mathf.Round(l.x * 100f) / 100f, ly = Mathf.Round(l.y * 100f) / 100f, lz = Mathf.Round(l.z * 100f) / 100f,
                        rx = Mathf.Round(r.x * 100f) / 100f, ry = Mathf.Round(r.y * 100f) / 100f, rz = Mathf.Round(r.z * 100f) / 100f,
                        hatId = localHatId,
                    }, "others");
                }
            }
#endif
#endif
        }

        public void RequestClaimPickup(int index)
        {
#if CCGD_MP
            if (GameNet.IsHost)
                TryClaimOnHost(index);
            else
                GameNet.SendData("claim_pickup", new ClaimPayload { index = index }, "host");
#else
            if (index >= 0 && index < SharedPickups.Length && SharedPickups[index] != null)
                SharedPickups[index].SetActive(false);
#endif
        }

#if CCGD_MP
        GameObject BuildPeerAvatar(NetPeer peer)
        {
            GameObject root = GameNet.MakeCapsuleAvatar(peer, radius: 0.32f, height: 1.55f);
            Transform left = GameObject.CreatePrimitive(PrimitiveType.Sphere).transform;
            Transform right = GameObject.CreatePrimitive(PrimitiveType.Sphere).transform;
            Destroy(left.GetComponent<Collider>());
            Destroy(right.GetComponent<Collider>());
            left.SetParent(root.transform, false);
            right.SetParent(root.transform, false);
            left.localScale = right.localScale = Vector3.one * 0.16f;
            left.localPosition = new Vector3(-0.35f, 1.05f, 0.28f);
            right.localPosition = new Vector3(0.35f, 1.05f, 0.28f);
            remoteHands[peer.Id] = (left, right, left.localPosition, right.localPosition);
            return root;
        }

        void OnClaimPickupRequest(string json, NetPeer from)
        {
            if (!GameNet.IsHost) return;
            var p = JsonUtility.FromJson<ClaimPayload>(json);
            TryClaimOnHost(p.index);
        }

        void OnRemoteVrHands(string json, NetPeer from)
        {
            if (!remoteHands.TryGetValue(from.Id, out var entry)) return;
            var p = JsonUtility.FromJson<VrHandsPayload>(json);
            remoteHands[from.Id] = (entry.left, entry.right, new Vector3(p.lx, p.ly, p.lz), new Vector3(p.rx, p.ry, p.rz));
        }

        void TryClaimOnHost(int index)
        {
            if (index < 0 || index >= SharedPickups.Length || !claimed.Add(index)) return;
            if (SharedPickups[index] != null) SharedPickups[index].SetActive(false);
            PublishClaimedState();
        }

        void PublishClaimedState()
        {
            var list = new List<object>(claimed.Count);
            foreach (int i in claimed) list.Add(i);
            GameNet.SetState("claimed", list);
        }

        void OnRoomStateChanged(string _)
        {
            int[] mask = GameNet.GetJson("claimed", Array.Empty<int>());
            claimed.Clear();
            foreach (int idx in mask) claimed.Add(idx);
            for (int i = 0; i < SharedPickups.Length; i++)
                if (SharedPickups[i] != null) SharedPickups[i].SetActive(!claimed.Contains(i));
        }

        void OnHostChanged(bool nowHost)
        {
            if (nowHost) PublishClaimedState();
        }
#endif

        void PlaceAtSpawnSlot(int slot)
        {
            if (LocalPlayer == null || SpawnPoints == null || SpawnPoints.Length == 0) return;
            Transform pt = SpawnPoints[Mathf.Abs(slot) % SpawnPoints.Length];
            LocalPlayer.SetPositionAndRotation(pt.position, pt.rotation);
        }
    }
}
```

## Performance & Platform Traps

- **Wrap All `GameNet` Calls in `#if CCGD_MP`**: Keep the component safe even if reused in a single-player scene.
- **Keep Room State Compact**: Put low-frequency shared truth (claimed masks, scores, round phase, boss/stalker state) in `GameNet.SetState`, never full vertex arrays or per-frame 60 Hz logs.
- **Disable Remote Avatar Colliders on Climbable/Ray Layers**: Remove colliders from remote hand spheres so teammates never block each other's raycasts or arm-push surface sweeps.

## Verification Checklist

1. Write a PlayMode test using `GameNet.Sim.AddPeer(...)`, `peer.SetPose(...)`, and `GameNet.TryGetPose(...)` verifying 2-peer avatar sync and shared pickup claiming.
2. Call `GameNet.Sim.DropHost()` in PlayMode and assert the local peer promotes cleanly (`GameNet.IsHost == true`) while preserving claimed pickup state.
3. Verify solo play (`GameNet.Active == false`) starts immediately with zero lobby blocking screen.

## Official references

- Glenn Fiedler (Gaffer on Games — Snapshot Interpolation & State Sync)
- GameCrew Unity 6 CCGD.GameNet Room Relay Specification
