GameCrew AIEarly access
Sign in
Unity 6gameplayRevision 1 · Compile-verified pattern

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

Updated

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.

  • dialogue
  • npc
  • conversation
  • rpg
  • cutscenes
  • camera
  • shop
  • cosmetics
  • coins
  • progression
  • inventory
  • mobile
  • ui
  • gameui
  • cloudsave

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)

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

More Unity 6 games

Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Unity 6 games here look like.

Fjordline — Leap from a granite wall under the midnight sun and carve one unbroken wingsuit line through Norway's most dramatic landscapes, from summit to sea, skimming close enough to touch the rock.

Fjordline

Leap from a granite wall under the midnight sun and carve one unbroken wingsuit line through Norway's most dramatic landscapes, from summit to sea, skimming close enough to touch the rock.

Saltwood Alley — Step up to the sunlit timber lanes of an old seaside arcade, feel the weight of turned maple in your palm, and bend real wrist-spin shots into tight vintage scoring cups.
Plays in VR

Saltwood Alley

Step up to the sunlit timber lanes of an old seaside arcade, feel the weight of turned maple in your palm, and bend real wrist-spin shots into tight vintage scoring cups.

More Unity 6 techniques

physics

Arcade Raycast Vehicle Physics, Enter/Exit Driving & Modular City RP Loop in Unity 6 →

Responsive raycast 4-wheel spring-damper vehicle physics in Unity 6 with speed-curved steering, handbrake drifting, seamless on-foot enter/exit vehicle handoff, and instanced modular city blocks with cheap waypoint traffic for WebGL.

ai

Context Steering, Telegraphed Combat & Attack-Token Encounters in Unity 6 →

Readable enemy and companion AI in Unity 6 using 8-ray context steering maps, FOV + line-of-sight hysteresis, telegraph/active/recovery state machines, and an encounter attack-token director.

gameplay

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.

gameplay

Frame-Rate-Independent Procedural Springs, Squash-Stretch & Trauma Feel in Unity 6 →

Exact dt-invariant second-order critically/under-damped spring dampers, Squirrel Eiserloh T^2 rotational Perlin camera trauma, volume-preserving squash-and-stretch, and TestClock-safe hit-stop.

Read via free MCP — or sign in to add techniques & beta test

Use /mcp/library free with no login to query guides, or connect via OAuth at /mcp to contribute technique guides and beta test cloud builds.

Connect via MCP