# Branching NPC Dialogue, Shot-Reverse-Shot Cutscenes, Cosmetics Shop & Safe-Area Mobile UI in Unity 6

> Complete RPG/social loop in Unity 6: data-driven branching NPC dialogue trees, VR-safe shot-reverse-shot cutscene cameras, coin/cosmetics unlock shop with CCGD.CloudSave persistence, and phone safe-area layout via CCGD.GameUI.PageInsets.

- **Canonical page:** https://gamecrew.ai/techniques/unity/dialogue-cutscenes-and-cosmetics-progression
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Unity 6
- **Category:** gameplay
- **Tags:** `dialogue`, `npc`, `conversation`, `rpg`, `cutscenes`, `camera`, `shop`, `cosmetics`, `coins`, `progression`, `inventory`, `mobile`, `ui`, `gameui`, `cloudsave`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-30)
- **Demo:** No demo

## When to Use (and When Not To)

Use this pattern for RPG/roleplay hubs, skateboard/snowboard career modes with story cutscenes, pet/character leveling games with cosmetics rooms (hats, collars, jackets, trails), haunted mall accessory shops, and mission-giver NPCs.

Keep dialogue concise (1–2 crisp lines per node, max 3 choices) so players read comfortably on both desktop monitors and vertical phones without text walls overlapping corner controls.

## Mathematical & Algorithmic Core

1. **Directed Dialogue Graph with Conditions & Effects**: Model conversations as flat `DialogueNode[]` arrays keyed by string ID (`id`, `speaker`, `line`, `cameraShot`, `choices[]` where each choice has `label`, `nextId`, optional `costCoins`, and optional `grantItemId`). Flat node arrays serialize trivially to JSON and are effortless to unit-test for dead ends or missing links.
2. **VR-Safe Shot-Reverse-Shot Cutscenes**: On flat screens (`!GameXR.Active`), smoothly damp the cutscene camera (`Vector3.SmoothDamp` + `Quaternion.Slerp`) between an establishing 2-shot and over-the-shoulder speaker framing, keeping both actors on the same side of the 180° line. Inside VR, NEVER hijack the headset camera — instead rotate the NPC to face `GameXR.Head` and show the dialogue on a diegetic `GameXR.Panel` at comfortable reading distance (`1.5 m`).
3. **Mobile Safe-Area Discipline (`CCGD.GameUI.PageInsets`)**: On upright iOS/Android phones, play-page corner buttons (sound, pause, room, fullscreen) occupy live screen insets. Anchor dialogue boxes to the bottom band (`20–26%` screen height) and read `GameUI.PageInsets` so coin counters and shop close buttons never collide with browser chrome.
4. **Cloud + Local Cosmetics Persistence**: Save unlocked item IDs, equipped slot IDs, and coin balance to `PlayerPrefs` immediately AND mirror to `CCGD.CloudSave.Save(json, merge: true)` when `CCGD.Account.SignedIn` is true so cosmetics survive browser reloads and new versions.

## Engine Implementation

### Branching Dialogue, Cosmetics Store & Cloud Persistence (`Assets/Game/Runtime/RPG/DialogueAndShopSystem.cs`)

```csharp
using System;
using System.Collections;
using System.Collections.Generic;
using CCGD;
using UnityEngine;

namespace Game.RPG
{
    [Serializable]
    public sealed class DialogueChoice
    {
        public string Label;
        public string NextNodeId;
        public int CostCoins;
        public string UnlockCosmeticId;
    }

    [Serializable]
    public sealed class DialogueNode
    {
        public string Id;
        public string Speaker;
        public string Text;
        public bool FocusNpc = true;
        public DialogueChoice[] Choices;
    }

    [Serializable]
    public sealed class PlayerCosmeticsSave
    {
        public int Coins;
        public string EquippedHat = "";
        public List<string> UnlockedIds = new List<string>();
    }

    public sealed class DialogueAndShopSystem : MonoBehaviour
    {
        [Header("Cutscene Anchors (Flat Screen Only)")]
        public Camera MainCamera;
        public Transform NpcShotAnchor;
        public Transform PlayerShotAnchor;
        public float CameraBlendSpeed = 7f;

        [Header("Cosmetic Attachment Slots")]
        public Transform HatMount;
        public GameObject[] HatPrefabs;

        public PlayerCosmeticsSave SaveData { get; private set; } = new PlayerCosmeticsSave();
        public DialogueNode ActiveNode { get; private set; }
        public bool InDialogue => ActiveNode != null;

        public event Action<DialogueNode> NodeChanged;
        public event Action<PlayerCosmeticsSave> InventoryChanged;

        readonly Dictionary<string, DialogueNode> nodesById = new Dictionary<string, DialogueNode>(StringComparer.Ordinal);
        Vector3 savedCamPos;
        Quaternion savedCamRot;
        bool camSaved;

        const string LocalSaveKey = "ccgd_cosmetics_v1";

        void Start()
        {
            LoadProgress();
        }

        public void RegisterDialogue(IEnumerable<DialogueNode> nodes)
        {
            nodesById.Clear();
            foreach (var n in nodes)
                if (n != null && !string.IsNullOrEmpty(n.Id)) nodesById[n.Id] = n;
        }

        public void StartDialogue(string startNodeId)
        {
            if (!nodesById.TryGetValue(startNodeId, out var node)) return;
            if (MainCamera != null && !IsVrActive())
            {
                savedCamPos = MainCamera.transform.position;
                savedCamRot = MainCamera.transform.rotation;
                camSaved = true;
            }
            ActiveNode = node;
            NodeChanged?.Invoke(ActiveNode);
        }

        public bool Choose(int choiceIndex)
        {
            if (ActiveNode == null || ActiveNode.Choices == null || choiceIndex < 0 || choiceIndex >= ActiveNode.Choices.Length)
                return false;

            DialogueChoice choice = ActiveNode.Choices[choiceIndex];
            if (choice.CostCoins > 0)
            {
                if (SaveData.Coins < choice.CostCoins) return false;
                SaveData.Coins -= choice.CostCoins;
            }
            if (!string.IsNullOrEmpty(choice.UnlockCosmeticId))
            {
                UnlockAndEquip(choice.UnlockCosmeticId);
            }

            if (!string.IsNullOrEmpty(choice.NextNodeId) && nodesById.TryGetValue(choice.NextNodeId, out var next))
            {
                ActiveNode = next;
                NodeChanged?.Invoke(ActiveNode);
            }
            else
            {
                EndDialogue();
            }
            PersistProgress();
            return true;
        }

        public void EndDialogue()
        {
            ActiveNode = null;
            if (camSaved && MainCamera != null && !IsVrActive())
            {
                MainCamera.transform.SetPositionAndRotation(savedCamPos, savedCamRot);
                camSaved = false;
            }
            NodeChanged?.Invoke(null);
        }

        public void AddCoins(int amount)
        {
            if (amount <= 0) return;
            SaveData.Coins += amount;
            InventoryChanged?.Invoke(SaveData);
            PersistProgress();
        }

        public void UnlockAndEquip(string cosmeticId)
        {
            if (string.IsNullOrEmpty(cosmeticId)) return;
            if (!SaveData.UnlockedIds.Contains(cosmeticId))
                SaveData.UnlockedIds.Add(cosmeticId);
            SaveData.EquippedHat = cosmeticId;
            ApplyEquippedVisuals();
            InventoryChanged?.Invoke(SaveData);
        }

        void Update()
        {
            if (!InDialogue || MainCamera == null || IsVrActive()) return;
            Transform anchor = ActiveNode.FocusNpc ? NpcShotAnchor : PlayerShotAnchor;
            if (anchor == null) return;
            float t = 1f - Mathf.Exp(-CameraBlendSpeed * Mathf.Min(Time.deltaTime, 0.05f));
            MainCamera.transform.position = Vector3.Lerp(MainCamera.transform.position, anchor.position, t);
            MainCamera.transform.rotation = Quaternion.Slerp(MainCamera.transform.rotation, anchor.rotation, t);
        }

        void ApplyEquippedVisuals()
        {
            if (HatMount == null || HatPrefabs == null) return;
            for (int i = HatMount.childCount - 1; i >= 0; i--) Destroy(HatMount.GetChild(i).gameObject);
            for (int i = 0; i < HatPrefabs.Length; i++)
            {
                if (HatPrefabs[i] != null && string.Equals(HatPrefabs[i].name, SaveData.EquippedHat, StringComparison.OrdinalIgnoreCase))
                {
                    Instantiate(HatPrefabs[i], HatMount, false);
                    break;
                }
            }
        }

        void LoadProgress()
        {
            string local = PlayerPrefs.GetString(LocalSaveKey, "");
            if (!string.IsNullOrEmpty(local))
            {
                var parsed = JsonUtility.FromJson<PlayerCosmeticsSave>(local);
                if (parsed != null) SaveData = parsed;
            }
            ApplyEquippedVisuals();
            StartCoroutine(LoadCloudRoutine());
        }

        IEnumerator LoadCloudRoutine()
        {
            yield return CloudSave.Load((ok, json) =>
            {
                if (!ok || string.IsNullOrEmpty(json)) return;
                var remote = JsonUtility.FromJson<PlayerCosmeticsSave>(json);
                if (remote != null && remote.Coins >= SaveData.Coins)
                {
                    SaveData = remote;
                    ApplyEquippedVisuals();
                    InventoryChanged?.Invoke(SaveData);
                }
            });
        }

        void PersistProgress()
        {
            string json = JsonUtility.ToJson(SaveData);
            PlayerPrefs.SetString(LocalSaveKey, json);
            StartCoroutine(CloudSave.Save(json, merge: true));
        }

        static bool IsVrActive()
        {
#if CCGD_VR
            return GameXR.Active;
#else
            return false;
#endif
        }
    }
}
```

## Performance & Platform Traps

- **Mobile Safe-Area Margins**: Keep top-right HUD coins/badges clear of `GameUI.PageInsets` so sound/pause buttons never cover currency labels on portrait phones (`390x844`).
- **Gamepad & Keyboard Navigation**: Allow `1/2/3` keys, D-pad/stick selection, and touch tap on every dialogue/shop button so desktop, gamepad, and mobile users can buy cosmetics effortlessly.
- **No Unreachable Graph Nodes**: Add an EditMode test asserting every `choice.NextNodeId` exists in `nodesById` and every conversation has a clean exit choice.

## Verification Checklist

1. In EditMode/PlayMode, traverse the dialogue tree, purchase a cosmetic with `AddCoins` + `Choose`, and confirm `SaveData.UnlockedIds` contains the item and `SaveData.Coins` decrements accurately.
2. Verify `EndDialogue()` restores the gameplay camera cleanly and re-enables player movement.
3. Capture phone (`390x844`) and desktop (`1280x720`) dialogue/shop views to confirm zero button clipping or HUD overlap.

## Official references

- Yarn Spinner & Ink Dialogue Graph Architecture
- Cinematography 180-Degree Shot-Reverse-Shot Framing
- GameCrew Unity 6 CCGD.GameUI & CCGD.CloudSave API
