重點摘要
把 NPC 模型放進 Workspace 中的 NPCs 資料夾,並把它的對話寫在 ReplicatedStorage 中的 ModuleScript:每一句台詞都有 NPC 的文字,以及會連到其他台詞的選項清單。ServerScriptService 中的 Script 替每個 NPC 加上 ProximityPrompt("Talk"),記住每位玩家目前在哪一句台詞,並透過 RemoteEvent 傳送它。LocalScript 顯示文字,並為每個選項顯示一個按鈕,傳回去的只有被按下按鈕的編號。
- 獎勵要在伺服器上發放。內建 Dialog 物件的
DialogChoiceSelected事件只會在用戶端觸發,所以伺服器 Script 永遠收不到它;而在 LocalScript 中發放的治療或道具,只會改變這位玩家那份遊戲副本。 - 從 LocalScript 用
TextChatService:DisplayBubble(npc.Head, text)顯示台詞的對話泡泡。舊的Chat服務已被淘汰,改用 TextChatService。 - 你自己寫的台詞不需要過濾。Roblox 的規則是:凡是你無法直接控制的顯示文字都要過濾,例如玩家輸入的內容。
NPC 對話的運作方式
在真正的遊戲中能運作的會說話 NPC,是分在伺服器與每位玩家的裝置兩邊的。裝置負責畫出視窗與按鈕。伺服器是唯一能信任的一方,它知道每位玩家正在讀哪一句台詞,並決定每個回答會做什麼。一回合的對話是這樣進行的:
- 玩家走近 NPC,在它的 Talk 提示上按 E。提示的
Triggered事件帶著這位玩家在伺服器上觸發。 - 伺服器 Script 確認玩家夠近,記住他在名為
start的台詞上,並只對這位玩家傳送這句台詞的文字與選項標籤。 - LocalScript 在對話視窗中逐字打出台詞,在 NPC 上方顯示對話泡泡,接著為每個選項加上一個按鈕。
- 玩家點擊、點按或選擇一個選項。傳回伺服器的只有它的編號。
- 伺服器在它知道玩家正在讀的那句台詞上找到這個編號,如果選項有動作(治療、道具)就執行它,然後傳送下一句台詞,或關閉視窗。
| 元件 | 位置 | 作用 |
|---|---|---|
Rig Guide | Workspace 中名為 NPCs 的資料夾 | NPC 本身。它的名稱決定使用哪段對話,也會顯示在提示上。 |
ModuleScript DialogueData | ReplicatedStorage | NPC 能說的所有台詞、每句台詞下的選項,以及每個選項會連到哪裡。 |
Script DialogueService | ServerScriptService | 加上 Talk 提示、記住每位玩家在哪一句台詞、檢查每次點擊並執行動作。 |
RemoteEvent DialogueEvent | ReplicatedStorage(由 DialogueService 建立) | 把每句台詞送給玩家,並把所選選項的編號送回伺服器。 |
LocalScript DialogueClient | StarterPlayer, StarterPlayerScripts | 畫出視窗、逐字打出台詞、顯示對話泡泡與選項按鈕。 |
Tool Torch(選用) | ServerStorage 中名為 DialogueItems 的資料夾 | 某個選項會給的道具。ServerStorage 中的東西不會傳給玩家。 |
Workspace
NPCs Folder new
Guide Model new
Humanoid Humanoid
HumanoidRootPart Part
Head、UpperTorso、LowerTorso ...(身體部位)
ReplicatedStorage
DialogueData ModuleScript new
ServerScriptService
DialogueService Script new
ServerStorage
DialogueItems Folder new
Torch Tool new
Handle Part new
StarterPlayer
StarterPlayerScripts
DialogueClient LocalScript new
步驟 1:加入 NPC
- 在 Avatar 或 Home 分頁按下 Character,開啟 Rig Generator。選擇 R15、體型與風格。Workspace 中會出現名為
Rig的 rig。R6 rig 也能用同樣的 Script。 - 把它改名為
Guide。名稱很重要:DialogueService 會依模型名稱尋找對話,提示也會把名稱顯示給玩家。 - 展開 rig,選取它的 HumanoidRootPart,在 Properties 視窗中勾選 Anchored。錨定的零件永遠不會因物理而移動,所以 NPC 會站在你放的位置,玩家也推不動它。
- 在 Explorer 中把滑鼠移到 Workspace 上,按下 + 按鈕,插入名為
NPCs的 Folder。把 Guide 拖進去,並把 rig 放在玩家走得到的地方。 - 選用,用於給道具的選項:把滑鼠移到 ServerStorage 上,插入名為
DialogueItems的 Folder。在裡面放一個名為Torch的 Tool,其中有一個沒有錨定、名為Handle的 Part,這就是角色拿在手上的零件。在 Handle 中放一個 PointLight,就能讓它發光。
名稱有大小寫之分,所以請完全照著輸入 NPCs、Guide、DialogueItems 與 Torch。任何有 Humanoid 與 HumanoidRootPart 的模型都能當 NPC,包括 Toolbox 中的模型,只要它直接放在 NPCs 資料夾中。
步驟 2:寫好對話
把滑鼠移到 ReplicatedStorage 上,插入名為 DialogueData 的 ModuleScript,貼上這段程式碼。裡面沒有邏輯,只有台詞與它們之間的連結,所以這是你最常修改的檔案。
-- 位於 ReplicatedStorage、名為 DialogueData 的 ModuleScript。
-- 所有對話,依 Workspace.NPCs 中的 NPC 名稱排列。每句台詞都有
-- NPC 的文字與玩家的回答選項。選項可以連到另一句台詞(next)、
-- 結束對話(沒有 next),也可以要求伺服器做某件事(action)。如果伺服器
-- 無法執行動作,就會顯示 failNext 台詞而不是 next。
export type Choice = {
text: string,
next: string?, -- 這個選項之後要顯示的台詞;nil 會結束對話
action: string?, -- DialogueService 中 ACTIONS 表格裡的伺服器動作
item: string?, -- 給 GiveItem 動作用:ServerStorage.DialogueItems 中 Tool 的名稱
failNext: string?, -- 動作無法執行時,用來取代 next 顯示的台詞
}
export type Line = {
text: string,
choices: { Choice },
}
local DialogueData: { [string]: { [string]: Line } } = {
Guide = {
start = {
text = "Welcome to the village! What can I do for you?",
choices = {
{ text = "Any tips?", next = "tips" },
{ text = "I'm hurt. Can you help?", next = "healed", action = "Heal", failNext = "healTooSoon" },
{ text = "Got anything for the cave?", next = "torch", action = "GiveItem", item = "Torch", failNext = "hasTorch" },
{ text = "Bye!" },
},
},
tips = {
text = "Stay off the red bricks, and come back if you get hurt.",
choices = {
{ text = "Anything else?", next = "start" },
{ text = "Thanks!" },
},
},
healed = {
text = "There you go, good as new.",
choices = {
{ text = "Thank you!" },
},
},
torch = {
text = "Take this torch. The cave is dark.",
choices = {
{ text = "Thanks!" },
},
},
healTooSoon = {
text = "I healed you a moment ago. Come back in a little while.",
choices = {
{ text = "OK" },
},
},
hasTorch = {
text = "You already have my torch. Keep it lit!",
choices = {
{ text = "Will do!" },
},
},
},
}
return DialogueData
開頭的 export type 幾行描述台詞與選項的樣子。遊戲進行時它們不會改變任何東西;它們描述你的資料,讓型別檢查可以檢查它。
各部分之間的關係:
- 每個 NPC 都有一張以它在 NPCs 資料夾中的模型命名的表格,這裡是
Guide。每段對話都從start台詞開始。 text是 NPC 說的話。choices是玩家的按鈕,依序排列。視窗中有四個按鈕的空間。next指定這個選項之後要顯示的台詞。沒有next的選項,例如 "Bye!",會結束對話。next或failNext指定了表格中不存在的台詞時,也會結束對話,並在 Output 中發出警告。action指定伺服器要做的事,來自 DialogueService 中的ACTIONS表格:這裡是Heal或GiveItem。item是給 GiveItem 用的:ServerStorage、DialogueItems 中 Tool 的名稱。failNext是動作無法執行時,取代next顯示的台詞,讓 NPC 永遠不會宣稱做了實際上沒發生的治療或贈禮。
| 台詞 | Guide 說 | 選項與去向 |
|---|---|---|
start | "Welcome to the village! What can I do for you?" | "Any tips?" 連到 tips。"I'm hurt. Can you help?" 會治療,接著是 healed(或 healTooSoon)。"Got anything for the cave?" 會給 Torch,接著是 torch(或 hasTorch)。"Bye!" 結束對話。 |
tips | "Stay off the red bricks, and come back if you get hurt." | "Anything else?" 回到 start。"Thanks!" 結束對話。 |
healed | "There you go, good as new." | "Thank you!" 結束對話。 |
torch | "Take this torch. The cave is dark." | "Thanks!" 結束對話。 |
healTooSoon | "I healed you a moment ago. Come back in a little while." | "OK" 結束對話。 |
hasTorch | "You already have my torch. Keep it lit!" | "Will do!" 結束對話。 |
只有伺服器會讀取這個模組。LocalScript 永遠不會 require 它:玩家走到哪一句台詞,伺服器就傳送哪一句。但 ReplicatedStorage 中的模組仍然會複製到每位玩家的裝置上,所以如果對話中有劇透(例如謎題的答案),請把 DialogueData 移到 ServerStorage。接著在 DialogueService 中有 require 的那一行,把 ReplicatedStorage 換成 ServerStorage,讓整行變成:local DialogueData = require(ServerStorage:WaitForChild("DialogueData")) :: { [string]: { [string]: Line } }。
步驟 3:加入伺服器 Script
把滑鼠移到 ServerScriptService 上,插入名為 DialogueService 的 Script,貼上下面的程式碼。這是唯一推進對話的地方,也是唯一發放獎勵的地方。
-- 位於 ServerScriptService、名為 DialogueService 的 Script。
-- 替 Workspace.NPCs 中的每個 NPC 加上 Talk 提示,並主導每一段對話。
-- 玩家的裝置只負責顯示文字,並傳回他點擊的選項編號。
-- 伺服器知道每位玩家在哪一句台詞,會檢查選項
-- 與距離,而且只有它能治療或發放道具。
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")
-- 和 DialogueData 中相同的型別,讓 Studio 的型別檢查在這裡也認得它們
type Choice = { text: string, next: string?, action: string?, item: string?, failNext: string? }
type Line = { text: string, choices: { Choice } }
local DialogueData = require(ReplicatedStorage:WaitForChild("DialogueData")) :: { [string]: { [string]: Line } }
local TALK_DISTANCE = 12 -- stud:提示的半徑,以及玩家必須保持多近
local MIN_SECONDS_BETWEEN_CHOICES = 0.3
local HEAL_COOLDOWN_SECONDS = 30
local npcFolder = workspace:WaitForChild("NPCs")
local itemFolder = ServerStorage:FindFirstChild("DialogueItems")
-- 這個 Script 會自己建立 DialogueEvent,所以不要手動加入
local dialogueEvent = Instance.new("RemoteEvent")
dialogueEvent.Name = "DialogueEvent"
dialogueEvent.Parent = ReplicatedStorage
type Conversation = { npc: Model, npcName: string, lineId: string, lastChoice: number }
local conversations: { [Player]: Conversation } = {}
local lastHeal: { [Player]: number } = {}
local function rootOf(model: Model?): BasePart?
local root = model and model:FindFirstChild("HumanoidRootPart")
return if root and root:IsA("BasePart") then root else nil
end
local function isClose(player: Player, npc: Model): boolean
local character = player.Character
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
local playerRoot = rootOf(character)
local npcRoot = rootOf(npc)
if not (humanoid and humanoid.Health > 0 and playerRoot and npcRoot) then
return false -- 沒有角色、角色已死亡,或 NPC 不見了
end
-- 留一點餘裕,因為玩家的位置傳到伺服器時會稍有延遲
return (playerRoot.Position - npcRoot.Position).Magnitude <= TALK_DISTANCE + 4
end
-- 選項有動作時伺服器要做的事。每個動作完成時傳回 true。
local ACTIONS: { [string]: (player: Player, choice: Choice) -> boolean } = {
Heal = function(player)
local now = os.clock()
if now - (lastHeal[player] or -math.huge) < HEAL_COOLDOWN_SECONDS then
return false -- 治療的時間太近了
end
local character = player.Character
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
if not (humanoid and humanoid.Health > 0) then
return false
end
lastHeal[player] = now
humanoid.Health = humanoid.MaxHealth
return true
end,
GiveItem = function(player, choice)
local itemName = choice.item
local template = itemFolder and itemName and itemFolder:FindFirstChild(itemName)
if not (itemName and template and template:IsA("Tool")) then
warn(`DialogueService: no Tool named {itemName} in ServerStorage.DialogueItems`)
return false
end
local backpack = player:FindFirstChildOfClass("Backpack")
local character = player.Character
if not backpack or backpack:FindFirstChild(itemName) or (character and character:FindFirstChild(itemName)) then
return false -- 還沒有背包,或他已經有這個道具
end
local item = template:Clone() :: Tool
item.CanBeDropped = false -- 讓任何人都無法把它丟掉再要一個
item.Parent = backpack
return true
end,
}
local function showLine(player: Player, conversation: Conversation)
local line = DialogueData[conversation.npcName][conversation.lineId]
local choiceTexts = {}
for _, choice in line.choices do
table.insert(choiceTexts, choice.text)
end
dialogueEvent:FireClient(player, "show", conversation.npc, line.text, choiceTexts)
end
local function endConversation(player: Player)
if conversations[player] then
conversations[player] = nil
dialogueEvent:FireClient(player, "close")
end
end
local function startConversation(player: Player, npc: Model)
local npcName = npc.Name
local lines = DialogueData[npcName]
if conversations[player] or not (lines and lines.start) or not isClose(player, npc) then
return -- 已經在對話中、這個 NPC 沒有 "start" 台詞、已死亡或距離太遠
end
local conversation = { npc = npc, npcName = npcName, lineId = "start", lastChoice = 0 }
conversations[player] = conversation
showLine(player, conversation)
end
-- 玩家點擊了編號為 choiceIndex 的選項(0 代表他關閉了視窗)
dialogueEvent.OnServerEvent:Connect(function(player: Player, choiceIndex: unknown)
local conversation = conversations[player]
if not conversation then
return
end
if typeof(choiceIndex) ~= "number" or choiceIndex ~= math.floor(choiceIndex) then
return
end
if choiceIndex == 0 or not isClose(player, conversation.npc) then
endConversation(player)
return
end
local now = os.clock()
if now - conversation.lastChoice < MIN_SECONDS_BETWEEN_CHOICES then
-- 太快了。再送一次同一句台詞,因為視窗在點擊後已經鎖住按鈕,
-- 否則它會永遠等待回覆。
showLine(player, conversation)
return
end
conversation.lastChoice = now
local line = DialogueData[conversation.npcName][conversation.lineId]
local choice = line.choices[choiceIndex]
if not choice then
return -- 這位玩家正在讀的台詞上沒有這個選項
end
local nextLine = choice.next
if choice.action then
local action = ACTIONS[choice.action]
local done = false
if action then
done = action(player, choice)
else
warn(`DialogueService: no action named {choice.action}`)
end
if not done and choice.failNext then
nextLine = choice.failNext -- 例如 "I healed you a moment ago"
end
end
if nextLine and not DialogueData[conversation.npcName][nextLine] then
warn(`DialogueService: no line named {nextLine} for {conversation.npcName} in DialogueData`)
nextLine = nil
end
if nextLine then
conversation.lineId = nextLine
showLine(player, conversation)
else
endConversation(player)
end
end)
-- 每個 NPC 上的 Talk 提示
local function setUpNpc(npc: Instance)
local root = if npc:IsA("Model") then rootOf(npc) else nil
if not (npc:IsA("Model") and root) then
return
end
if not (DialogueData[npc.Name] and DialogueData[npc.Name].start) then
warn(`DialogueService: no conversation with a start line for {npc.Name} in DialogueData`)
end
local leftover = root:FindFirstChild("TalkPrompt")
if leftover then
leftover:Destroy() -- NPC 的複本會帶著沒有人在監聽的舊提示
end
local prompt = Instance.new("ProximityPrompt")
prompt.Name = "TalkPrompt"
prompt.ActionText = "Talk"
prompt.ObjectText = npc.Name
prompt.MaxActivationDistance = TALK_DISTANCE
prompt.RequiresLineOfSight = false
prompt.Parent = root
prompt.Triggered:Connect(function(player: Player)
startConversation(player, npc)
end)
end
for _, npc in npcFolder:GetChildren() do
setUpNpc(npc)
end
npcFolder.ChildAdded:Connect(setUpNpc)
-- 對話中途離開或死亡的人,一律關閉視窗
task.spawn(function()
while true do
task.wait(0.5)
for player, conversation in conversations do
if not isClose(player, conversation.npc) then
endConversation(player)
end
end
end
end)
Players.PlayerRemoving:Connect(function(player: Player)
conversations[player] = nil
lastHeal[player] = nil
end)
DialogueService 會在遊戲開始時自己建立 RemoteEvent DialogueEvent,所以不需要手動在 ReplicatedStorage 插入任何東西。如果你已經建立了同名的 RemoteEvent,請刪除它:LocalScript 可能會找到你那個,而伺服器上沒有人在監聽它。
| 設定 | 這裡的值 | 改變什麼 |
|---|---|---|
TALK_DISTANCE | 12 | 玩家要離多近(單位 stud)才會出現 Talk 提示。伺服器會讓他再走遠 4 stud 才關閉視窗,因為玩家的位置傳到伺服器時會稍有延遲。 |
MIN_SECONDS_BETWEEN_CHOICES | 0.3 | 伺服器接受的兩次點擊之間的最短時間。比這更快的點擊,會收到同一句台詞而不是回答。 |
HEAL_COOLDOWN_SECONDS | 30 | 每位玩家在兩次 Heal 動作治療之間要等多久。 |
伺服器在 conversations 中為每位玩家保存一筆紀錄:他在和哪個 NPC 說話、正在讀哪一句台詞,以及他上一次被接受的點擊是什麼時候。Talk 提示觸發時,startConversation 只有在玩家還沒在對話中、NPC 有 start 台詞,而且玩家活著又在範圍內時,才會建立這筆紀錄。之後每一次點擊都要通過下列檢查:
| 檢查 | 程式碼 | 沒通過時 |
|---|---|---|
| 玩家正在對話中 | conversations[player] | 忽略這次點擊。 |
| 選項是整數 | typeof 與 math.floor | 忽略。字串、表格、小數與 NaN 會在這裡被擋下。 |
| 0 代表玩家按了 X | choiceIndex == 0 | 對話結束。 |
| 活著,而且距離仍在 16 stud 內(12 加 4) | isClose | 對話結束,視窗關閉。 |
| 距離上一次被接受的點擊至少 0.3 秒 | conversation.lastChoice | 再送一次同一句台詞,讓視窗拿到新的按鈕,而不是永遠等待。 |
| 選項存在於這位玩家正在讀的台詞上 | line.choices[choiceIndex] | 忽略。 |
| 動作成功 | 每個動作都傳回 true 或 false | 顯示 failNext 台詞,而不是 next。 |
提示掛在 NPC 的 HumanoidRootPart 上,因為 ProximityPrompt 要放在 Workspace 中的零件(或 Attachment,或有 PrimaryPart 的模型)內才會運作。它的 RequiresLineOfSight 預設是開啟的,只要有東西擋住從攝影機到這個零件的視線,就會隱藏提示。Roblox 會把提示自己所在的零件排除在這項檢查之外,但身體的其他部分不會,而 HumanoidRootPart 位在軀幹裡面,所以 Script 關閉了視線檢查。提示的名稱是 TalkPrompt,Script 在加上自己的提示之前,會先刪除零件上已有的任何 TalkPrompt:遊戲進行中做出的 NPC 複本會帶著原本的提示,而複製來的提示沒有人在監聽。如果 DialogueData 中沒有這個 NPC 名稱、含 start 台詞的對話,Output 中會出現帶有這個 NPC 名稱的警告。
一個迴圈每秒檢查每段進行中的對話兩次,當玩家走到 16 stud 以外或他的角色死亡時就關閉它,讓在對話中途死亡的玩家不會帶著開著的視窗重生。有人離開時,PlayerRemoving 會清空兩張表格。
步驟 4:加入對話視窗
打開 StarterPlayer,把滑鼠移到 StarterPlayerScripts 上,插入名為 DialogueClient 的 LocalScript,貼上這段程式碼。它用程式碼組出對話視窗,所以不需要手動畫 GUI。
-- 位於 StarterPlayer > StarterPlayerScripts、名為 DialogueClient 的 LocalScript。
-- 畫出伺服器傳來的對話:NPC 的名稱、一個字一個字打出的
-- 台詞、頭上的對話泡泡,以及每個選項一個按鈕。點擊
-- 選項只會傳送它的編號;接下來會發生什麼,由伺服器決定。
local GuiService = game:GetService("GuiService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local TextChatService = game:GetService("TextChatService")
local UserInputService = game:GetService("UserInputService")
local dialogueEvent = ReplicatedStorage:WaitForChild("DialogueEvent") :: RemoteEvent
local player = Players.LocalPlayer
local LETTERS_PER_SECOND = 45
local REGULAR = Font.fromEnum(Enum.Font.BuilderSans)
local BOLD = Font.fromEnum(Enum.Font.BuilderSansBold)
-- 用程式碼組出的對話視窗
local gui = Instance.new("ScreenGui")
gui.Name = "Dialogue"
gui.ResetOnSpawn = false
gui.Enabled = false
local box = Instance.new("Frame")
box.AnchorPoint = Vector2.new(0.5, 1)
box.Position = UDim2.new(0.5, 0, 1, -84) -- 往上移 84 像素,讓 Roblox 的工具列不會擋住選項
box.Size = UDim2.fromScale(0.6, 0.34)
box.BackgroundColor3 = Color3.fromRGB(24, 24, 32)
box.BackgroundTransparency = 0.1
box.Parent = gui
local corner = Instance.new("UICorner")
corner.CornerRadius = UDim.new(0, 12)
corner.Parent = box
local sizeLimit = Instance.new("UISizeConstraint")
sizeLimit.MaxSize = Vector2.new(720, 300)
sizeLimit.Parent = box
local nameLabel = Instance.new("TextLabel")
nameLabel.Position = UDim2.fromScale(0.04, 0.04)
nameLabel.Size = UDim2.fromScale(0.8, 0.14)
nameLabel.BackgroundTransparency = 1
nameLabel.TextXAlignment = Enum.TextXAlignment.Left
nameLabel.TextColor3 = Color3.fromRGB(190, 160, 255)
nameLabel.TextScaled = true
nameLabel.FontFace = BOLD
nameLabel.Parent = box
local lineLabel = nameLabel:Clone()
lineLabel.Position = UDim2.fromScale(0.04, 0.2)
lineLabel.Size = UDim2.fromScale(0.92, 0.3)
lineLabel.TextColor3 = Color3.new(1, 1, 1)
lineLabel.TextScaled = true -- 長台詞會縮小,以便放進小小的手機畫面
lineLabel.TextWrapped = true
lineLabel.TextYAlignment = Enum.TextYAlignment.Top
lineLabel.FontFace = REGULAR
lineLabel.Parent = box
local lineTextLimit = Instance.new("UITextSizeConstraint")
lineTextLimit.MaxTextSize = 20 -- 在大螢幕上也永遠不會超過 20 像素
lineTextLimit.Parent = lineLabel
local closeButton = Instance.new("TextButton")
closeButton.AnchorPoint = Vector2.new(1, 0)
closeButton.Position = UDim2.new(1, -8, 0, 8)
closeButton.Size = UDim2.fromOffset(32, 32)
closeButton.BackgroundTransparency = 1
closeButton.Text = "X"
closeButton.TextColor3 = Color3.new(1, 1, 1)
closeButton.TextSize = 20
closeButton.FontFace = BOLD
closeButton.Parent = box
local choiceList = Instance.new("Frame")
choiceList.Position = UDim2.fromScale(0.04, 0.52)
choiceList.Size = UDim2.fromScale(0.92, 0.44)
choiceList.BackgroundTransparency = 1
choiceList.Parent = box
local layout = Instance.new("UIGridLayout")
layout.CellSize = UDim2.new(0.5, -6, 0.5, -6)
layout.CellPadding = UDim2.fromOffset(6, 6)
layout.SortOrder = Enum.SortOrder.LayoutOrder
layout.Parent = choiceList
gui.Parent = player:WaitForChild("PlayerGui")
local talkingTo: Model? = nil
local lineNumber = 0 -- 每來一句新台詞就加一,讓舊的打字迴圈停下
local function setPromptVisible(npc: Model?, visible: boolean)
local root = npc and npc:FindFirstChild("HumanoidRootPart")
local prompt = root and root:FindFirstChild("TalkPrompt")
if prompt and prompt:IsA("ProximityPrompt") then
prompt.Enabled = visible -- 只會在這台裝置上改變
end
end
local function clearChoices()
for _, child in choiceList:GetChildren() do
if child:IsA("TextButton") then
child:Destroy()
end
end
end
local function close()
lineNumber += 1
clearChoices()
gui.Enabled = false
setPromptVisible(talkingTo, true)
talkingTo = nil
GuiService.SelectedObject = nil
end
local function show(npc: Model, text: string, choices: { string })
lineNumber += 1
local thisLine = lineNumber
if talkingTo ~= npc then
setPromptVisible(talkingTo, true)
talkingTo = npc
setPromptVisible(npc, false)
end
gui.Enabled = true
nameLabel.Text = npc.Name
clearChoices()
-- NPC 上方的對話泡泡(DisplayBubble 只能在 LocalScript 中使用)
local head = npc:FindFirstChild("Head")
if head then
TextChatService:DisplayBubble(head, text)
end
-- 一個字一個字打出台詞。字數是依經過的時間計算的,
-- 所以在任何幀率下速度都一樣。
lineLabel.Text = text
lineLabel.MaxVisibleGraphemes = 0
local letters = 0
for _ in utf8.graphemes(text) do
letters += 1
end
local startTime = os.clock()
local shown = 0
while shown < letters do
task.wait()
if lineNumber ~= thisLine then
return -- 這句台詞已被更新的台詞或關閉取代
end
shown = math.min(letters, math.floor((os.clock() - startTime) * LETTERS_PER_SECOND))
lineLabel.MaxVisibleGraphemes = shown
end
lineLabel.MaxVisibleGraphemes = -1
-- 每個選項一個按鈕;伺服器只會收到按鈕的編號
for index, choiceText in choices do
local button = Instance.new("TextButton")
button.LayoutOrder = index
button.BackgroundColor3 = Color3.fromRGB(124, 77, 255)
button.TextColor3 = Color3.new(1, 1, 1)
button.TextScaled = true
button.FontFace = BOLD
button.Text = choiceText
local buttonCorner = Instance.new("UICorner")
buttonCorner.CornerRadius = UDim.new(0, 8)
buttonCorner.Parent = button
button.Parent = choiceList
button.Activated:Connect(function()
if lineNumber == thisLine then
lineNumber += 1 -- 每句台詞只能點一次
dialogueEvent:FireServer(index)
end
end)
if index == 1 and UserInputService.PreferredInput == Enum.PreferredInput.Gamepad then
GuiService.SelectedObject = button -- 讓選項可以用手把選擇
end
end
end
closeButton.Activated:Connect(function()
dialogueEvent:FireServer(0)
close()
end)
dialogueEvent.OnClientEvent:Connect(function(kind: string, npc: Model?, text: string?, choices: { string }?)
if kind == "show" and npc and text and choices then
show(npc, text, choices)
elseif kind == "close" then
close()
end
end)
顏色、大小與 LETTERS_PER_SECOND 可以隨意修改。最後兩個處理函式請保持原樣:它們是視窗和伺服器溝通的唯一方式。
DialogueClient 每個部分的作用:
- 視窗。一個 ScreenGui,裡面的 Frame 固定在畫面下方正中央,寬度為畫面的 60%、高度為 34%,並透過
UISizeConstraint限制在 720 x 300 像素,不會在寬螢幕上整個拉開。NPC 的台詞使用TextScaled,在小小的手機畫面上會縮小文字以放進標籤,而UITextSizeConstraint讓它在大螢幕上不會超過 20 像素。UIGridLayout把選項排成兩列兩欄。ResetOnSpawn為 false,因為這個 LocalScript 每個遊戲階段只執行一次:重生時被刪除的視窗就不會再回來了。 - 打字機效果。整句台詞一次放進 TextLabel,由
MaxVisibleGraphemes決定能看到幾個字元;Roblox 自己的打字機範例搭配utf8.graphemes使用的也是這個屬性。Roblox 會以所有字元都可見的方式排版文字,所以字詞在出現的過程中不會跳到下一行,也不會改變大小。Script 依經過的時間計算要顯示幾個字元,每秒 45 個,所以在任何幀率下速度都一樣,最後再把這個屬性設為 -1,也就是全部顯示。 - 按鈕。台詞打完時才會出現。每個按鈕只傳送自己的編號,而且只傳一次:
lineNumber檢查讓連點兩下也不會傳送兩次,之後視窗會等待伺服器傳來下一句台詞。 - 台詞對話泡泡。
TextChatService:DisplayBubble(head, text)把台詞放進 NPC Head 上方的聊天泡泡中。Roblox 只允許在用戶端 Script 中這樣做,而 bubble chat 預設是開啟的。泡泡是這位玩家的裝置畫的,所以只有他看得到。 - 提示。玩家在對話時,他那份 Talk 提示(依名稱 TalkPrompt 找到)會被關閉,不會一直浮在對話上方。其他玩家仍然看得到他們自己的提示。
- 任何裝置。滑鼠點擊、手機點按與手把的 A 鍵都會觸發
Activated。手把只能按下被選取的按鈕,所以當PreferredInput表示玩家使用手把時,Script 會透過GuiService.SelectedObject選取第一個選項。 - X 按鈕。它會傳送 0,伺服器會把它理解為「結束對話」,並立刻關閉視窗。
加入你自己的動作
動作就是 DialogueService 開頭 ACTIONS 表格中的一個函式。它接收玩家與選項,完成工作時傳回 true。要加入你自己的動作,例如 NPC 發放的任務:
- 在
ACTIONS中加入名為StartQuest的項目。先檢查,再修改:如果player:GetAttribute("Quest")已經有值,就傳回false;否則呼叫player:SetAttribute("Quest", "Cave")並傳回true。 - 在 DialogueData 中替選項設定
action = "StartQuest"、成功時的next台詞,以及失敗時的failNext台詞,例如 "You are already on a quest." - 按下 Play,把這個選項選兩次。如果 DialogueData 中的名稱和
ACTIONS中的鍵不一致(大小寫有差別),Output 會出現DialogueService: no action named StartQuest,對話會跳到failNext台詞。
撰寫動作的規則:
- 檢查與修改都在動作裡、在伺服器上進行。玩家裝置唯一會傳送的,就是選項編號。
- 動作需要的東西,要從選項(像
item)或伺服器自己的狀態讀取,絕不能從 remote 讀取。 - 任何有價值的東西都要在動作本身裡面設限,就像 Heal 在
lastHeal中保存自己 30 秒的冷卻時間。每次點擊 0.3 秒的限制只會放慢點擊速度;它無法阻止玩家一次又一次走過同一個選項。 - 要打開別的視窗,例如商店,動作可以對這位玩家傳送 RemoteEvent 並傳回
true。那個視窗中發生的一切仍然需要自己的伺服器檢查,就像 NPC 商人一節所說的。
其他 NPC 對話教學錯在哪裡
如果你拿這篇教學和影片或論壇文章比較,以下是重要的差異,以及每種做法會造成問題的原因。
| 教學 | 問題 | 本教學 |
|---|---|---|
使用 Dialog 物件,並讓伺服器 Script 監聽 DialogChoiceSelected 來發放獎勵 | Roblox 參考文件寫道,這個事件只在用戶端運作,不會在伺服器上觸發,所以獎勵永遠不會發出。 | 選項以數字傳到伺服器,由伺服器自己發放獎勵。 |
| 從 LocalScript 發放獎勵 | LocalScript 做的修改只會留在那一台裝置上(請看哪些東西會複寫),而作弊者隨時都能執行同一段程式碼。 | 所有動作都放在 DialogueService 中。 |
透過 game:GetService("Chat"):Chat(head, text) 讓 NPC 說話 | Chat 服務已被淘汰,改用 TextChatService。 | 在 LocalScript 中使用 TextChatService:DisplayBubble。 |
| 從用戶端傳送獎勵名稱或下一句台詞的 id | 作弊者可以傳送任何道具名稱,或直接跳到會給獎勵的台詞。 | 用戶端只傳送選項編號。伺服器在它知道玩家正在讀的台詞上找到這個編號。 |
| 提示觸發後什麼都不檢查 | Roblox 的安全教學把 ProximityPrompt 和 remote 並列為用戶端可能濫用的東西,並建議在執行動作前檢查玩家是否夠近。 | 在對話開始時、每次點擊時,以及對話進行中每秒兩次檢查距離。 |
在迴圈中用 wait() 逐字打出文字 | 全域的 wait 已被淘汰,改用 task.wait。 | 依 os.clock() 計算可見的字數,並用 task.wait() 等待。 |
玩家能偽造與不能偽造的東西
請假設作弊者能控制他裝置上的一切。他可以讀取你的 LocalScript 與 ReplicatedStorage 中的一切、用任何參數任意次數呼叫 DialogueEvent,也可以用程式碼觸發 Talk 提示,這正是 Roblox 安全教學所警告的。DialogueService 用同一類伺服器檢查來應對,和 RemoteEvent 參數檢查一節介紹的一樣。以下是作弊者能從中得到的東西。
| 作弊者嘗試 | 結果 | 原因 |
|---|---|---|
| 從地圖另一端觸發 Talk 提示 | 什麼都不會發生 | startConversation 會檢查他是否在 16 stud 內(12 加 4)。 |
| 傳送選項 99、字串、小數或 NaN | 被忽略 | 它不是整數,或他正在讀的台詞上沒有這個選項。 |
| 傳送獎勵名稱或台詞 id | 永遠不會被讀取 | 伺服器只讀取選項編號。獎勵來自伺服器那份台詞的 item 與 action 欄位。 |
| 以網路允許的最快速度點擊 | 每段對話每 0.3 秒一次點擊 | 更快的點擊只會拿回同一句台詞。結束並重新開始對話可以繞過這個等待,所以 Heal 與 GiveItem 各自有自己的限制。 |
| 不經對話就要火把 | 不可能 | 只有在伺服器知道玩家所在的那句台詞上選擇選項,才會發放道具。 |
| 囤積一大堆火把 | 一次只有一支 | 伺服器會先在他的 Backpack 與角色中尋找 Torch,而發出的火把不能丟掉,所以無法靠丟掉再要來刷火把。 |
| 狂刷治療台詞 | 每 30 秒治療一次 | 冷卻時間在伺服器上依玩家分別保存,NPC 會用 healTooSoon 台詞告訴他。 |
| 走開並讓視窗一直開著 | 半秒內關閉 | 伺服器每秒檢查每段進行中的對話兩次。 |
| 讀取整段對話,包括他還沒走到的台詞 | 有可能 | DialogueData 放在 ReplicatedStorage,會複製到每一台裝置上。如果這很重要,就把它移到 ServerStorage(請看步驟 2)。 |
有一個限制值得直接說明:走到 Guide 面前選擇選項的作弊者,得到的東西和正常玩家完全一樣。伺服器控制的是頻率與地點,而不是對象。任何稀有的東西,例如每位玩家只能領一次的獎勵,都需要由伺服器掌握的檢查,例如在領取時設定的屬性,或存在資料儲存中的旗標。
步驟 5:測試
- 按下 Play(F5),走向 Guide。在 12 stud 內會出現帶有 Guide 名稱的 Talk 提示。按下 E。
- 視窗顯示 "Guide",逐字打出歡迎台詞,接著顯示四個按鈕。同一句台詞也會出現在 NPC 頭上的對話泡泡中。
- 選擇 "Any tips?",再選 "Anything else?":你回到了第一句台詞。選擇 "Bye!":視窗關閉,Talk 提示重新出現。
- 先讓自己受傷:按下 Client/Server 切換按鈕切到 Server,在 Workspace 中選取你角色的 Humanoid,在 Properties 視窗中把 Health 設為 50,再切回 Client。玩家角色每秒會恢復 MaxHealth 的 1%,所以請馬上和 Guide 說話並選擇 "I'm hurt. Can you help?":生命值會一下子補滿。在 30 秒內再說一次話並再選一次:不會治療,Guide 會說它剛剛才治療過你。
- 選擇 "Got anything for the cave?":Torch 出現在快捷列中。裝備它並按下 Backspace:它還留在手上。再要一次:不會有第二支火把,Guide 會說你已經有了。
- 開始對話後走開。大約在你離 Guide 16 stud 時,視窗就會關閉。
- 在測試模式下拉選單中選擇 Server & Clients,設 2 個用戶端,按下 Play。兩位玩家可以同時和 Guide 說話,各自在自己的台詞上。
- 試玩測試時,用 Controller Emulator(Emulation 分頁中的 Controller)測試手把。用模擬手把走過去,按下提示按鍵(預設為 ButtonX):選項出現時,第一個已經被選取,按 A 就會按下它。
- 用 Studio 的 Device Simulator 測試手機畫面(撰寫本文時它是 Beta:在 File、Beta Features 中開啟 New Device Simulator 並重新啟動 Studio)。選擇一支手機,按 Rotate 直到它變成橫向,按下 Play,走向 Guide 並點按 Talk 提示。選擇 "Any tips?":整句台詞都會顯示在選項按鈕上方,必要時文字會變小,而且不會壓到按鈕。
整個過程中都保持 Output 視窗開著(Window 選單,再選 Output)。這些 Script 正常運作時不會印出任何東西,所以任何紅色錯誤或以 DialogueService: 開頭的警告都是真正的問題。請看常見錯誤。
如何擴充
更多 NPC 與更長的對話
在 NPCs 資料夾中加入另一個有自己名稱的 rig,並在 DialogueData 中加入同名、含 start 台詞的表格。DialogueService 會替資料夾中每個有 HumanoidRootPart 的模型加上 Talk 提示,包括遊戲進行中才加入的;NPC 的複本會拿到新的提示,而不是複製來的那個。兩個同名的 NPC 會共用同一張表格。台詞可以用任何順序互相連結,選項也可以連回較早的台詞,就像 "Anything else?"。每句台詞最多放四個選項,因為視窗會把它們排成兩列兩欄。
依進度改變的台詞
要用不同的方式迎接回來的玩家,就依伺服器掌握的資訊選擇第一句台詞。在 startConversation 中用 local firstLine = if player:GetAttribute("MetGuide") then "welcomeBack" else "start" 來選擇,像 Script 檢查 lines.start 那樣確認這句台詞存在,並在建立對話時用 firstLine 取代 "start"。在動作中設定這個屬性,並在 Guide 的表格中加入 welcomeBack 台詞。屬性只存在於一個遊戲階段;要在多次造訪之間記住玩家,就像 DataStore 教學那樣把旗標存在資料儲存中。
NPC 商人
照著商店 GUI 教學做出商店,再加入一個 OpenShop 動作,對這位玩家傳送 RemoteEvent 並傳回 true,然後讓商店的 LocalScript 在收到這個事件時打開它的視窗。購買仍然經過商店自己的伺服器檢查。如果只能在 NPC 旁邊購買,請也在購買處理函式中檢查距離,因為用戶端可以從任何地方呼叫商店的 remote。
會走動的 NPC
要讓 Guide 四處閒逛或跟著玩家,請使用 NPC 尋路教學,並取消 HumanoidRootPart 的 Anchored,讓它能移動。Talk 提示掛在這個零件上,所以會跟著 NPC 移動,距離檢查也使用同一個零件。對話進行中請暫停走動,否則只要 NPC 離玩家超過 16 stud,視窗就會關閉。
鑰匙、任務與其他獎勵
GiveItem 可以發放 DialogueItems 中的任何 Tool,所以 NPC 可以給出上鎖的門會檢查的鑰匙,就像門的教學那樣。使用時會有作用的道具,例如能治療的食物,請看背包教學。
音效與攝影機
要讓每句台詞有語音片段或短音效,就在 NPC 的 Head 中放一個 Sound,並在 DialogueClient 的 show 中播放它。要在 NPC 說話時把攝影機對準它,過場動畫教學示範了 LocalScript 如何接管攝影機,再把控制權還回去。
常見錯誤與解法
按下 Play 之前先打開 Output 視窗(Window 選單,再選 Output)。大多數對話問題不是會在那裡印出警告,就是因為名稱不一致而發生。
Infinite yield possible on 'ReplicatedStorage:WaitForChild("DialogueEvent")'
DialogueClient 在等 DialogueService 建立的 remote,代表 DialogueService 沒有執行到那裡。請確認它是 Script 而不是 LocalScript、直接放在 ServerScriptService 中,而且沒有被停用。DialogueService 會先等待 ReplicatedStorage 中的 DialogueData 與 Workspace 中的 NPCs 資料夾,所以缺少它們或名稱打錯也會讓它停住;這時 Output 會顯示 DialogueService 發出、帶有那個名稱的 infinite yield 警告。
我的 NPC 上方沒有出現 Talk 提示
DialogueService 只會替直接放在 Workspace、NPCs 中,而且有名為 HumanoidRootPart 零件的模型加上提示。檢查這兩個條件,並走到 12 stud 以內。Toolbox 的 rig 可能沒有這個零件,或者它可能是包在資料夾裡、類型不同的物件。
提示出現了,但按 E 沒有反應
伺服器找不到這個 NPC 的對話,遊戲開始時 Output 會顯示帶有你 NPC 名稱的 DialogueService: no conversation with a start line for Guide in DialogueData。DialogueData 中的表格名稱必須和模型完全相同,包括大寫字母,而且要有 start 台詞。
選項會關閉視窗,而不是前往下一句台詞
Output 會顯示帶有你的名稱的 DialogueService: no line named tip for Guide in DialogueData:選項的 next(或 failNext)指定了這個 NPC 表格中不存在的台詞。台詞名稱有大小寫之分,所以請對照表格檢查拼字,這裡應該是 tips。
視窗能用,但沒有台詞的對話泡泡
對話泡泡需要 NPC 模型中直接有一個名為 Head 的零件,而且 bubble chat 要開啟:在 Explorer 中選取 TextChatService 底下的 BubbleChatConfiguration,確認 Enabled 已勾選。它預設是開啟的。
Output 寫著 DialogueService: no Tool named Torch in ServerStorage.DialogueItems
伺服器找不到道具。請確認 ServerStorage 中的資料夾名為 DialogueItems,裡面有一個 Tool(不是 Model,也不是 Part),名稱和選項的 item 完全相同。在你修正之前,Guide 會用 hasTorch 台詞回答,因為動作失敗了。
Output 寫著 DialogueService: no action named ...
選項的 action 和 ACTIONS 表格中的任何鍵都不相符。名稱有大小寫之分:heal 不等於 Heal。
用 RoCode 製作
如果你覺得描述 NPC 比自己動手組裝更簡單,RoCode 可以直接在你開啟的場景中寫出這些 Script。它是 Roblox Studio 的獨立 AI 代理,並非 Roblox 官方產品:你在網頁聊天中輸入,它的 Studio 外掛程式會在你的 Explorer 中建立並編輯 Script。
讓 Workspace.NPCs 中的 Guide 模型能說話:Talk 提示、會逐字打出台詞並有選項按鈕的對話視窗、頭上的對話泡泡、冷卻時間 30 秒的治療選項,以及一個只會發放一次 ServerStorage 中 Torch 工具的選項。把對話存在 ModuleScript 中,所有獎勵都在伺服器上發放。
- 可以先用 Get Properties 檢查模型,讀取關鍵數值,例如零件的 Anchored 與 Humanoid 的 WalkSpeed。在聊天中輸入 / 就能附上模型的精確路徑
- 用 Create Script 寫出 ModuleScript DialogueData、Script DialogueService 與 LocalScript DialogueClient
- 它被指示用 Check Script 確認每一個寫好的 Script 都能編譯,Check Script 會在 Studio 中編譯它而不執行
- 分批送出變更,每一批都是 Studio 歷程中的一個復原點
外掛程式 3.9 或更新版本時,RoCode 可以執行一次簡短的試玩測試並讀取錯誤;外掛程式 3.9.11 或更新版本時,它可以操作測試角色來確認遊戲能運作,但遊戲進行中它不會截圖,所以請自己走到 NPC 面前和它說話。如果有東西運作不對,把你看到的情況告訴 RoCode:Check Output 可以讀取你上一次試玩測試的 Server 與 Client 訊息。會說話的 NPC 只是眾多系統之一;如何用 AI 製作 Roblox 遊戲,每個提示詞一個系統這一頁說明了它們如何組合在一起。RoCode 如何連接到 Studio。
常見問題
Roblox Studio 中怎麼做會說話的 NPC?
替 NPC 加上 ProximityPrompt,玩家觸發它時,在對話視窗、對話泡泡或兩者中顯示 NPC 的台詞。這篇教學的三個 Script 兩者都做,還加上回答選項。如果只需要對話泡泡,就在提示觸發時從 LocalScript 呼叫 TextChatService:DisplayBubble(npc.Head, "Hello!"),就像 Roblox bubble chat 頁面上的 NPC 範例。
該選哪個:Dialog 物件還是自製的對話 GUI?
Dialog 物件不需要程式碼,會顯示可點擊的泡泡,裝飾性文字這樣就夠了。它的選擇事件只在玩家裝置上觸發,所以無法安全地發放獎勵,而且預設同一時間只有一位玩家能和它說話。像這篇教學這樣自製視窗,能讓伺服器發放每一項獎勵,並讓每位玩家擁有自己的對話。
怎麼讓 NPC 給玩家道具?
把 Tool 放在 ServerStorage,當玩家選擇那個選項時,讓伺服器 Script 把它複製到玩家的 Backpack,就像 GiveItem 動作那樣。確認玩家還沒有這個道具,並關閉複本的 CanBeDropped,讓它無法被丟掉再要一次。永遠不要讓玩家的裝置決定要發哪個道具。
怎麼做出有打字機效果的對話視窗?
把整句台詞放進 TextLabel,讓它的 MaxVisibleGraphemes 從 0 開始每次增加幾個字元,最後設為 -1 全部顯示。Roblox 的 UI 動畫頁面搭配 utf8.graphemes 使用的也是這個屬性。DialogueClient 依經過的時間計算要顯示幾個字元,每秒 45 個,所以速度與幀率無關。
兩位玩家可以同時和同一個 NPC 說話嗎?
用這篇教學的 Script 可以:伺服器為每位玩家各自維持一段對話,每位玩家只看得到自己的視窗。內建的 Dialog 物件則不同:在它預設的 BehaviorType,也就是 SinglePlayer 下,一次只有一位玩家能說話,其他人會看到他的選項。
NPC 對話的文字需要過濾嗎?
你自己寫的台詞不需要。Roblox 要求你負責過濾你無法直接控制的顯示文字,例如玩家輸入的內容、由隨機字元組成的字詞,或從外部網站載入的文字。如果 NPC 會重複玩家輸入的東西,就過濾那一部分。
來源與延伸閱讀
- Roblox Creator Docs:Proximity prompts(英文). 建立提示、MaxActivationDistance 與 RequiresLineOfSight
- Roblox Engine API:ProximityPrompt(英文). 提示在哪裡能運作、它的文字與預設按鍵、Triggered 與視線檢查
- Roblox Creator Docs:Securing the client-server boundary(英文). ProximityPrompt 作為攻擊面、距離與權限檢查
- Roblox Engine API:Dialog(英文). BehaviorType 與只在用戶端觸發的 DialogChoiceSelected 事件
- Roblox Engine API:TextChatService:DisplayBubble(英文). 從用戶端 Script 顯示 NPC 的台詞泡泡
- Roblox Creator Docs:Customize bubble chat(英文). NPC 的對話泡泡與 BubbleChatConfiguration
- Roblox Creator Docs:Text filtering(英文). 哪些顯示文字需要過濾
- Roblox Creator Docs:UI animation and tweens(英文). 用 MaxVisibleGraphemes 做打字機效果
- Roblox Engine API:Tool.CanBeDropped(英文). Backspace 會對工具做什麼
- Roblox Engine API:UserInputService.PreferredInput(英文). 如何判斷玩家使用手把
- Roblox Creator Docs:Rig Generator(英文). 插入 R15 或 R6 rig
程式碼如何驗證:本頁每一段 Script 都通過 Luau 嚴格型別檢查,並使用 Roblox API 定義(luau-lsp,2026年11月20日)。型別檢查能找出拼錯的 API 與錯誤的型別,但無法檢查遊戲邏輯,所以發布前請先在 Studio 中測試。