教學 · 遊戲系統

如何在 Roblox Studio 製作商店

Roblox 遊戲中的商店是兩件事:顯示商品的 GUI,以及決定購買是否成立的伺服器 Script。這篇教學會替販售工具的金幣商店把兩者都做出來,並說明 Robux 購買該放在哪裡。

更新日期 2026年11月20日閱讀約 3 分鐘作者

重點摘要

把商品與價格放在 ReplicatedStorage 中的 ModuleScript,用 ScreenGui、ScrollingFrame 與 UIGridLayout 組出視窗,讓每個 Buy 按鈕呼叫 RemoteFunction,而且只傳送商品 id。接著由 ServerScriptService 中的 Script 自己找出價格、檢查並扣除玩家的 Coins,再發放商品。

  • 絕對不要讓用戶端傳送價格。任何人都能用任何數值呼叫你的 remote,所以伺服器要從自己那份目錄取得價格。
  • 購買的 Tool 要從 ServerStorage 複製到玩家的 Backpack(馬上就能用)與 StarterGear(重生後還會回來)。
  • 用 Robux 販售的是通行證與 developer product,由 MarketplaceService 處理。Roblox 還會自動替它們建立 Shop,而那和金幣商店不是同一個東西。
本頁內容
  1. 組成方式
  2. 1. 準備
  3. 2. 商品目錄
  4. 3. 商店 GUI
  5. 4. 伺服器購買
  6. 為什麼不傳價格
  7. 5. 測試
  8. 遊戲通行證
  9. 儲存購買
  10. Common errors
  11. 用 RoCode
  12. 常見問題
  13. 來源與延伸閱讀

能運作的商店是怎麼組成的

示意畫面玩家打開商店,用 25 枚金幣買下 Flashlight:Coins 從 200 降到 175,按鈕變成 Owned,工具出現在快捷列中。

在真正的遊戲中能運作的商店,是分成玩家的裝置與伺服器兩邊的。裝置負責畫出視窗並說「我想買劍」。伺服器是唯一能信任的一方,由它決定這件事會不會發生。那些「沒有作用」或被玩家用外掛破解的商店 Script,往往都是在錯誤的一邊做了這個決定。

商店的五個部分
部分位置作用
ModuleScript ShopCatalogReplicatedStorage商品 id、名稱、價格,以及每個商品給的 Tool。兩邊都會讀取它。
RemoteFunction BuyItemReplicatedStorage 的 ShopRemotes 資料夾中把購買請求送到伺服器,並把回覆傳回來。
LocalScript ShopClientStarterPlayerScripts組出商店視窗,在按下 Buy 按鈕時傳送商品 id。
Script ShopServiceServerScriptService檢查請求、扣除 Coins 並發放 Tool。
你要賣的 ToolServerStorage 的 ShopItems 資料夾中伺服器複製用的原件。ServerStorage 中的東西不會傳給玩家。
商店完成後的 Explorer
ReplicatedStorage
  ShopCatalog ModuleScript new
  ShopRemotes Folder new
    BuyItem RemoteFunction new
ServerStorage
  ShopItems Folder new
    ClassicSword Tool new
      Handle Part
    Flashlight Tool new
    GrappleHook Tool new
    SpeedCoil Tool new
ServerScriptService
  Leaderstats Script
  ShopService Script new
StarterPlayer
  StarterPlayerScripts
    ShopClient LocalScript new

步驟 1:金幣與要販售的商品

商店會花用玩家 leaderstats 中的 Coins 數值。如果你做過排行榜教學,你已經有它了,可以跳過這個 Script。否則請在 ServerScriptService 中插入一個名為 Leaderstats 的 Script。它會在開始時給每個人 200 枚金幣,讓你可以馬上測試購買。

Script 位於 ServerScriptService 名稱為 Leaderstats
local Players = game:GetService("Players")

local STARTING_COINS = 200 -- 足夠測試商店;等玩家可以賺金幣時改成 0

local function setupLeaderstats(player: Player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"

	local coins = Instance.new("IntValue")
	coins.Name = "Coins"
	coins.Value = STARTING_COINS
	coins.Parent = leaderstats

	leaderstats.Parent = player
end

Players.PlayerAdded:Connect(setupLeaderstats)
for _, player in Players:GetPlayers() do
	setupLeaderstats(player)
end

只保留一個 leaderstats Script。兩個各自建立 leaderstats 資料夾的 Script,會讓每位玩家有兩個資料夾,商店可能會讀到錯的那一個。

接著建立 Script 要找的物件。名稱有分大小寫,請完全照這裡的寫法。

  1. 在 Explorer 中把游標移到 ReplicatedStorage 上,按 + 按鈕,插入一個名為 ShopRemotes 的 Folder。在裡面插入一個名為 BuyItem 的 RemoteFunction。
  2. 把游標移到 ServerStorage 上,插入一個名為 ShopItems 的 Folder。
  3. 在 ShopItems 中替每個商品放一個 Tool,名稱分別為 ClassicSword、Flashlight、GrappleHook 與 SpeedCoil。第一次測試時,Tool 裡只要有一個未 Anchored、名為 Handle 的 Part 就夠了。你已經有的任何 Tool 也可以用:給它正確的名稱即可。真的會造成傷害的武器,請照著劍的教學或槍的教學做;每一篇都說明了如何接上目錄。
  4. 選取每個 Tool,在 Properties 視窗中取消勾選 CanBeDropped。勾選時,按 Backspace 會把工具丟到 Workspace,任何玩家都能撿走購買者付錢買的東西。

你也可以只用一個 Tool 開始。如果某個商品缺少 Tool,伺服器會拒絕販售該商品,並寫出帶有名稱的警告,所以玩家不會被扣任何錢。

步驟 2:目錄中的商品與價格

目錄是商店販售的所有東西的唯一清單。LocalScript 讀取它來畫出卡片,伺服器讀取它來找價格,所以改價格只要在一個地方改一次。

把游標移到 ReplicatedStorage 上,插入一個 ModuleScript,改名為 ShopCatalog,並把內容換成這段:

ModuleScript 位於 ReplicatedStorage 名稱為 ShopCatalog
export type ShopItem = {
	id: string, -- 之後會存進 data store:玩家已經擁有這個商品後就不要再改
	name: string, -- 顯示在卡片上;可以修改
	price: number, -- 以 Coins 計
	description: string,
	toolName: string, -- 玩家拿到的 ServerStorage.ShopItems 中的 Tool
}

-- 卡片依這個順序出現
local items: { ShopItem } = {
	{
		id = "sword",
		name = "Classic Sword",
		price = 50,
		description = "A basic sword for close fights.",
		toolName = "ClassicSword",
	},
	{
		id = "flashlight",
		name = "Flashlight",
		price = 25,
		description = "Lights up dark corners.",
		toolName = "Flashlight",
	},
	{
		id = "grapple",
		name = "Grapple Hook",
		price = 150,
		description = "Reach high ledges.",
		toolName = "GrappleHook",
	},
	{
		id = "speedcoil",
		name = "Speed Coil",
		price = 300,
		description = "Run faster while you hold it.",
		toolName = "SpeedCoil",
	},
}

local byId: { [string]: ShopItem } = {}
for _, item in items do
	byId[item.id] = item
end

local ShopCatalog = {}

ShopCatalog.items = items

-- 回傳這個 id 的商品,沒有這個商品時回傳 nil
function ShopCatalog.get(id: string): ShopItem?
	return byId[id]
end

-- 玩家擁有商品時,伺服器會設為 true 的 Player 屬性
function ShopCatalog.ownedAttribute(id: string): string
	return "Owns_" .. id
end

return ShopCatalog

每個商品都有一個 id,以及另外用來顯示的 name。玩家擁有某樣東西時,伺服器記錄的是 id,所以之後可以把「Classic Sword」改名而不會弄壞已儲存的購買紀錄。說明只是卡片上的文字;Tool 做什麼由它自己的 Script 決定。

玩家可以讀取 ReplicatedStorage 中的 ModuleScript,所以這些價格是公開的。這沒關係:它們本來就寫在卡片上。重要的是用戶端和伺服器各自執行自己那份模組,所以在自己裝置上改價格的玩家,不會改變伺服器上的任何東西。

步驟 3:組出商店 GUI

這個 LocalScript 用程式碼組出整個視窗:Shop 按鈕、有可捲動卡片格的面板、目錄中每個商品各一個 Buy 按鈕、Coins 計數器,以及顯示伺服器回覆的狀態列。因為全部都是用程式碼做的,貼上就能按 Play。後面的表格列出每一個物件,讓你想手動排版時參考。

  1. 在 Explorer 中展開 StarterPlayer,把游標移到 StarterPlayerScripts 上,插入一個名為 ShopClient 的 LocalScript。
  2. 把它的內容換成下面的程式碼。
LocalScript 位於 StarterPlayerScripts 名稱為 ShopClient
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

-- ShopCatalog 模組回傳的東西,讓嚴格型別檢查能檢查我們用到的欄位
type ShopItem = { id: string, name: string, price: number, description: string, toolName: string }
type Catalog = {
	items: { ShopItem },
	get: (id: string) -> ShopItem?,
	ownedAttribute: (id: string) -> string,
}

local ShopCatalog = require(ReplicatedStorage:WaitForChild("ShopCatalog")) :: Catalog
local buyItem = ReplicatedStorage:WaitForChild("ShopRemotes"):WaitForChild("BuyItem") :: RemoteFunction

local player = Players.LocalPlayer

local COLOURS = {
	panel = Color3.fromRGB(24, 20, 36),
	card = Color3.fromRGB(38, 32, 56),
	accent = Color3.fromRGB(124, 77, 255),
	owned = Color3.fromRGB(70, 66, 84),
	text = Color3.fromRGB(240, 238, 245),
	muted = Color3.fromRGB(170, 165, 185),
	good = Color3.fromRGB(120, 220, 150),
}
local REGULAR = Font.fromEnum(Enum.Font.BuilderSans)
local BOLD = Font.fromEnum(Enum.Font.BuilderSansBold)

local function addCorner(parent: GuiObject, radius: number)
	local corner = Instance.new("UICorner")
	corner.CornerRadius = UDim.new(0, radius)
	corner.Parent = parent
end

local function addPadding(parent: GuiObject, pixels: number)
	local padding = Instance.new("UIPadding")
	padding.PaddingTop = UDim.new(0, pixels)
	padding.PaddingBottom = UDim.new(0, pixels)
	padding.PaddingLeft = UDim.new(0, pixels)
	padding.PaddingRight = UDim.new(0, pixels)
	padding.Parent = parent
end

local function newLabel(parent: GuiObject, text: string, textSize: number, font: Font): TextLabel
	local label = Instance.new("TextLabel")
	label.BackgroundTransparency = 1
	label.Text = text
	label.TextSize = textSize
	label.FontFace = font
	label.TextColor3 = COLOURS.text
	label.TextXAlignment = Enum.TextXAlignment.Left
	label.TextWrapped = true
	label.Parent = parent
	return label
end

local function newButton(parent: GuiObject, text: string): TextButton
	local button = Instance.new("TextButton")
	button.BackgroundColor3 = COLOURS.accent
	button.TextColor3 = COLOURS.text
	button.FontFace = BOLD
	button.TextSize = 18
	button.Text = text
	button.Parent = parent
	addCorner(button, 8)
	return button
end

-- ScreenGui:存放商店畫在玩家畫面上的所有東西
local gui = Instance.new("ScreenGui")
gui.Name = "ShopGui"
gui.ResetOnSpawn = false -- 角色重生時商店會保留

-- 左側邊緣用來開關商店的按鈕
local openButton = Instance.new("TextButton")
openButton.Name = "OpenShop"
openButton.AnchorPoint = Vector2.new(0, 0.5)
openButton.Position = UDim2.new(0, 16, 0.5, 0)
openButton.Size = UDim2.fromOffset(110, 44)
openButton.BackgroundColor3 = COLOURS.accent
openButton.TextColor3 = COLOURS.text
openButton.FontFace = BOLD
openButton.TextSize = 20
openButton.Text = "Shop"
openButton.Parent = gui
addCorner(openButton, 10)

-- 商店視窗:置中,玩家打開之前是隱藏的
local panel = Instance.new("Frame")
panel.Name = "Panel"
panel.AnchorPoint = Vector2.new(0.5, 0.5)
panel.Position = UDim2.fromScale(0.5, 0.5)
panel.Size = UDim2.fromScale(0.8, 0.75)
panel.BackgroundColor3 = COLOURS.panel
panel.Visible = false
panel.Parent = gui
addCorner(panel, 14)
addPadding(panel, 12)

local sizeLimit = Instance.new("UISizeConstraint")
sizeLimit.MaxSize = Vector2.new(640, 460) -- 避免視窗在大螢幕上變得超大
sizeLimit.Parent = panel

local title = newLabel(panel, "Shop", 26, BOLD)
title.Size = UDim2.new(0.5, 0, 0, 32)

local coinsLabel = newLabel(panel, "Coins: ...", 20, BOLD)
coinsLabel.AnchorPoint = Vector2.new(1, 0)
coinsLabel.Position = UDim2.new(1, -44, 0, 0)
coinsLabel.Size = UDim2.new(0.5, -44, 0, 32)
coinsLabel.TextXAlignment = Enum.TextXAlignment.Right

local closeButton = newButton(panel, "X")
closeButton.AnchorPoint = Vector2.new(1, 0)
closeButton.Position = UDim2.fromScale(1, 0)
closeButton.Size = UDim2.fromOffset(32, 32)
closeButton.BackgroundColor3 = COLOURS.card

-- 這裡顯示伺服器的回覆,例如 "You need 20 more coins."
local status = newLabel(panel, "", 18, REGULAR)
status.AnchorPoint = Vector2.new(0, 1)
status.Position = UDim2.fromScale(0, 1)
status.Size = UDim2.new(1, 0, 0, 24)
status.TextColor3 = COLOURS.muted

-- ScrollingFrame:卡片多到放不下時可以捲動的區域
local list = Instance.new("ScrollingFrame")
list.Name = "Items"
list.Position = UDim2.fromOffset(0, 44)
list.Size = UDim2.new(1, 0, 1, -76)
list.BackgroundTransparency = 1
list.BorderSizePixel = 0
list.ScrollBarThickness = 6
list.ScrollingDirection = Enum.ScrollingDirection.Y
list.CanvasSize = UDim2.new() -- 從零開始;AutomaticCanvasSize 會依卡片撐大
list.AutomaticCanvasSize = Enum.AutomaticSize.Y
list.Parent = panel

-- UIGridLayout:把卡片排成一列一列,並換到下一列
local grid = Instance.new("UIGridLayout")
grid.CellSize = UDim2.fromOffset(180, 200)
grid.CellPadding = UDim2.fromOffset(12, 12)
grid.SortOrder = Enum.SortOrder.LayoutOrder
grid.Parent = list

local function makeCard(item: ShopItem, order: number)
	local card = Instance.new("Frame")
	card.Name = item.id
	card.LayoutOrder = order
	card.BackgroundColor3 = COLOURS.card
	card.Parent = list
	addCorner(card, 10)
	addPadding(card, 10)

	local nameLabel = newLabel(card, item.name, 20, BOLD)
	nameLabel.Size = UDim2.new(1, 0, 0, 26)

	local description = newLabel(card, item.description, 15, REGULAR)
	description.Position = UDim2.fromOffset(0, 30)
	description.Size = UDim2.new(1, 0, 1, -80)
	description.TextColor3 = COLOURS.muted
	description.TextYAlignment = Enum.TextYAlignment.Top

	local buyButton = newButton(card, "")
	buyButton.Name = "Buy"
	buyButton.AnchorPoint = Vector2.new(0, 1)
	buyButton.Position = UDim2.fromScale(0, 1)
	buyButton.Size = UDim2.new(1, 0, 0, 40)

	local ownedAttribute = ShopCatalog.ownedAttribute(item.id)
	local busy = false

	local function refresh()
		if player:GetAttribute(ownedAttribute) == true then
			buyButton.Text = "Owned"
			buyButton.BackgroundColor3 = COLOURS.owned
			buyButton.AutoButtonColor = false
		else
			buyButton.Text = `Buy: {item.price} coins`
			buyButton.BackgroundColor3 = COLOURS.accent
			buyButton.AutoButtonColor = true
		end
	end

	buyButton.Activated:Connect(function()
		if busy or player:GetAttribute(ownedAttribute) == true then
			return
		end
		busy = true
		buyButton.Text = "Buying..."

		-- 只傳送商品 id。價格由伺服器自己找。
		local ok, bought, message = pcall(function()
			return buyItem:InvokeServer(item.id)
		end)
		if ok and type(message) == "string" then
			status.Text = message
			status.TextColor3 = if bought == true then COLOURS.good else COLOURS.muted
		else
			status.Text = "The shop did not answer. Try again."
			status.TextColor3 = COLOURS.muted
		end

		busy = false
		refresh()
	end)

	-- 購買成功時(或已儲存的商品載入時),伺服器會設定這個屬性
	player:GetAttributeChangedSignal(ownedAttribute):Connect(refresh)
	refresh()
end

for index, item in ShopCatalog.items do
	makeCard(item, index)
end

openButton.Activated:Connect(function()
	panel.Visible = not panel.Visible
	status.Text = ""
end)

closeButton.Activated:Connect(function()
	panel.Visible = false
end)

gui.Parent = player:WaitForChild("PlayerGui")

-- 顯示玩家的金幣。真正的數值在伺服器上;這裡只負責顯示。
local leaderstats = player:WaitForChild("leaderstats")
local coins = leaderstats:WaitForChild("Coins") :: IntValue
local function updateCoins()
	coinsLabel.Text = `Coins: {coins.Value}`
end
coins.Changed:Connect(updateCoins)
updateCoins()

按鈕使用 Activated,而不是 MouseButton1Click:它會在滑鼠點擊、手機觸控,以及手把的 A 鍵或叉叉鍵時觸發。

開頭的 type 定義描述 ShopCatalog 回傳的東西,讓嚴格型別檢查能抓到欄位的拼字錯誤,例如 item.prise。遊戲執行時它們不會改變任何東西。

GUI 物件與重要屬性
物件在商店中的工作主要屬性
ScreenGui存放畫在畫面上的所有東西ResetOnSpawn 為 false,讓商店在重生後仍保留
Frame視窗與每一張商品卡片AnchorPoint 0.5, 0.5 與 Position 0.5, 0.5,讓視窗置中
UISizeConstraint在大螢幕上限制視窗大小MaxSize 640 x 460
ScrollingFrame卡片多到放不下時可以捲動CanvasSize 0 與 AutomaticCanvasSize Y,讓捲動區域隨卡片變大
UIGridLayout把卡片排成一列一列並換行CellSize 180 x 200、CellPadding 12、SortOrder LayoutOrder
UICorner讓邊角變圓CornerRadius 8 到 14 像素
UIPadding內距每一邊 10 到 12 像素
TextButtonShop、關閉與 Buy 按鈕Activated 事件

如果想手動畫出視窗,就在 StarterGui 中用這些屬性組出同樣的物件,在那裡也把 ScreenGui 的 ResetOnSpawn 設為 false,並保留一張卡片當作範本,讓 LocalScript 替目錄中的每個商品複製。這樣 Script 只需要填入卡片並串接按鈕。下一步的購買邏輯完全不變。

如果你的遊戲從主選單開始,那篇教學中有一行要加進 ShopClient,讓 Shop 按鈕只在玩家按下 Play 後才出現。要讓商店透過和商人對話打開,NPC 對話教學示範如何加入叫 ShopClient 開啟視窗的 OpenShop 動作,而購買仍然經過商店的伺服器檢查。

步驟 4:在伺服器上檢查與購買

這個 Script 是唯一能發生購買的地方。它接收商品 id、檢查它、找出價格、檢查玩家的 Coins,然後扣除金幣並發放 Tool。它會回覆 Buy 按鈕 true 或 false,以及要顯示的訊息。

把游標移到 ServerScriptService 上,插入一個名為 ShopService 的 Script,並貼上這段:

Script 位於 ServerScriptService 名稱為 ShopService
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")

-- ShopCatalog 模組回傳的東西,讓嚴格型別檢查能檢查我們用到的欄位
type ShopItem = { id: string, name: string, price: number, description: string, toolName: string }
type Catalog = {
	items: { ShopItem },
	get: (id: string) -> ShopItem?,
	ownedAttribute: (id: string) -> string,
}

local ShopCatalog = require(ReplicatedStorage:WaitForChild("ShopCatalog")) :: Catalog
local buyItem = ReplicatedStorage:WaitForChild("ShopRemotes"):WaitForChild("BuyItem") :: RemoteFunction
local shopItems = ServerStorage:WaitForChild("ShopItems")

local COOLDOWN_SECONDS = 0.5
local lastRequest: { [Player]: number } = {}

local function giveTool(player: Player, template: Tool)
	-- Backpack:玩家可以馬上使用工具
	local backpack = player:FindFirstChildOfClass("Backpack")
	if backpack then
		template:Clone().Parent = backpack
	end
	-- StarterGear:每次角色出現時,Roblox 都會再把它複製到 Backpack
	local starterGear = player:FindFirstChildOfClass("StarterGear")
	if starterGear then
		template:Clone().Parent = starterGear
	end
end

local function onBuyItem(player: Player, itemId: unknown): (boolean, string)
	-- 1. 用戶端只傳送商品 id,所以它必須是字串
	if type(itemId) ~= "string" then
		return false, "That item does not exist."
	end

	-- 2. 忽略連點與 Script 送來的大量請求
	local now = os.clock()
	local last = lastRequest[player]
	if last and now - last < COOLDOWN_SECONDS then
		return false, "Slow down a little."
	end
	lastRequest[player] = now

	-- 3. 在伺服器自己那份目錄中找商品
	local item = ShopCatalog.get(itemId)
	if not item then
		return false, "That item does not exist."
	end

	local ownedAttribute = ShopCatalog.ownedAttribute(item.id)
	if player:GetAttribute(ownedAttribute) == true then
		return false, "You already own this."
	end

	local template = shopItems:FindFirstChild(item.toolName)
	if not (template and template:IsA("Tool")) then
		warn(`ShopItems has no Tool named {item.toolName} for shop item {item.id}`)
		return false, "This item is not available right now."
	end

	local leaderstats = player:FindFirstChild("leaderstats")
	local coins = leaderstats and leaderstats:FindFirstChild("Coins")
	if not (coins and coins:IsA("IntValue")) then
		return false, "Your coins have not loaded yet."
	end

	-- 4. 價格取自目錄,永遠不從用戶端取得
	if coins.Value < item.price then
		return false, `You need {item.price - coins.Value} more coins.`
	end

	-- 5. 先扣金幣,再發放商品。這裡沒有任何會讓出執行的地方,所以同一位玩家的兩個請求
	-- 不可能在這段執行完之前都通過上面的檢查。
	coins.Value -= item.price
	giveTool(player, template)
	player:SetAttribute(ownedAttribute, true)

	return true, `You bought {item.name}.`
end

buyItem.OnServerInvoke = onBuyItem

Players.PlayerRemoving:Connect(function(player: Player)
	lastRequest[player] = nil
end)

擁有權以 Player 屬性儲存,例如 Owns_sword。伺服器設定的屬性會複寫到玩家的裝置,所以 LocalScript 能把卡片切換成「Owned」。玩家在自己那份副本中做的修改不會傳到伺服器。

Tool 會放到兩個地方。Backpack 中的副本會馬上出現在快捷列。StarterGear 中的副本,Roblox 會在每次角色出現時放進新的 Backpack。少了它,購買的商品會在玩家第一次死亡時消失。

為什麼用戶端永遠不傳送價格

玩家裝置上的任何東西,玩家都能修改。作弊者會在自己那份遊戲中執行自己的程式碼:他們能讀你的 LocalScript、改 GUI,並用任何參數呼叫 BuyItem:InvokeServer() 任意多次。Roblox 的安全指南說,remote 收到的所有東西都要檢查型別與數值,而那裡舉的例子正好就是商店。

如果伺服器信任用戶端會發生什麼事
作弊者送出如果伺服器相信他ShopService 怎麼做
價格 0所有商品都免費忽略它。價格取自目錄。
價格 -1000Coins.Value -= -1000 會給他 1,000 枚金幣忽略它。
以 NaN 當作價格任何和 NaN 的比較都是 false,所以「金幣不夠」的檢查永遠不會觸發忽略它。
目錄中沒有的 id,或用表格取代字串Script 出錯,或賣出你不打算賣的東西回覆「That item does not exist.」
每秒幾百個請求伺服器負載,而檢查中的任何漏洞都會被觸發幾百次每位玩家每半秒最多處理一個請求。
在自己畫面上改過的 Coins用自己沒有的金幣購買完全看不到。伺服器只讀取自己的 Coins 數值。

這條規則適用於你寫的每一個 remote:傳送玩家選了什麼,例如商品 id 或欄位編號,而永遠不要傳送它值多少錢或他應該得到什麼。RemoteEvent 教學更詳細地說明如何檢查 remote 的參數。

步驟 5:測試商店

  1. 按下 Play。左邊會出現 Shop 按鈕。打開它並購買 Flashlight:Coins 會減少 25,工具出現在快捷列中,它的按鈕會變成 Owned。
  2. 試試 300 枚金幣的 Speed Coil。狀態列會寫出還差多少金幣,而且不會扣任何錢。
  3. 用遊戲內選單重設角色。因為 StarterGear 中有副本,Flashlight 會回到新的 Backpack 中。
  4. 測試時要替自己加金幣,請按 Client/Server 切換到 Server,在 Explorer 中找到 Players、你的名字、leaderstats、Coins,並在 Properties 視窗中修改它的 Value。在 Client 模式下做同樣的事只會改變你的畫面,而這正是伺服器會忽略的那種修改。

如果按鈕回覆「The shop did not answer」,請從 Studio 的 Window 選單開啟 Output 視窗,找出 ShopService 的紅色錯誤。如果按鈕一直停在「Buying...」,表示 ShopService 沒有在執行,或卡在等待某個物件:請見常見錯誤。

用 Robux 販售遊戲通行證

金幣是你自己的貨幣,所以上面的商店會自己決定每一筆購買。玩家用 Robux 購買的東西運作方式不同:遊戲通行證只買一次、永久保留(VIP 加成、永久工具),developer product 則可以一買再買(一包金幣、跳關)。兩者都透過 Roblox 的 MarketplaceService,收款的是 Roblox,而不是你的 Script。

這篇教學有兩條規則可以沿用:在用戶端用按鈕開啟購買視窗,只在 Roblox 確認購買或玩家已經擁有通行證時,才在伺服器上發放加成。遊戲通行證 Script 教學完整做出這些:進入時檢查擁有權、購買視窗、VIP 門這類加成,以及什麼時候用 developer product 比通行證好。要決定價格時,免費的 Robux 抽成計算機會顯示通行證或 developer product 扣掉 Roblox 的分成後你能拿到多少。

儲存玩家的購買

到目前為止我們做的東西只存在一次遊戲期間:在你用 data store 儲存之前,玩家離開時金幣和購買的商品都會重設。為了不在這裡重複儲存的程式碼,請看 DataStore 教學(或排行榜教學的步驟 3,那裡的版本比較短),並記住商店的規則:

  • 把商品的 id,例如 { "sword", "flashlight" },和 Coins 數值存在同一張表格中,讓一次儲存同時記下花掉的金幣與買到的商品。Tool 和其他 Instance 無法存進 data store。
  • 資料載入後,走過儲存的 id,略過目錄中已經沒有的,設定每一個 Owns_ 屬性,並像 giveTool 那樣發放 Tool。商店視窗會自己更新,因為它在監聽這些屬性。
  • 通行證的擁有權不需要儲存:UserOwnsGamePassAsync 會在每次玩家進入時詢問 Roblox。
  • 絕對不要儲存資料沒有載入成功的玩家,否則一次失敗的載入可能會用空清單蓋掉他的購買紀錄。

常見錯誤與解法

商店行為怪異時,先檢查這些。第一步請開啟 Output 視窗(Window 選單,再選 Output):Script 錯誤會指出是哪個 Script 和哪一行。

Infinite yield possible on 'ReplicatedStorage:WaitForChild("ShopRemotes")'

Script 在等待一個不存在、或名稱不完全相同的物件。請檢查 ShopRemotes、BuyItem、ShopCatalog 與 ShopItems 的拼字和大小寫,並確認 ShopItems 放在 ServerStorage 而不是 ReplicatedStorage。Script 錯誤教學詳細說明了這個警告。

Buy 按鈕停在「Buying...」沒有回應

伺服器上沒有人設定 BuyItem.OnServerInvoke,所以 Roblox 會一直保留請求,直到有人設定為止。確認 ShopService 是 Script 而不是 LocalScript,而且放在 ServerScriptService 中,並在 Output 中尋找 ShopService 的 Infinite yield possible 警告:它代表 Script 卡在等待 ShopCatalog、ShopRemotes 或 ShopItems。

Buy 按鈕顯示「The shop did not answer」

伺服器呼叫失敗,而不是回傳了回覆。常見的原因是 ShopService 在處理請求時出錯,所以請在 Output 中找出 ShopService 的紅色錯誤:裡面會寫出是哪一行。

按鈕顯示「This item is not available right now」

伺服器在 ServerStorage 的 ShopItems 中找不到這個商品 toolName 的 Tool。Output 中有一則警告,寫出它找的確切名稱。

我買了工具,但角色拿不起來或會卡住

Tool 裡面必須正好有一個直接放在裡面、名為 Handle 的零件,而且它的零件都不能是 Anchored。不需要拿在手上的工具,請改為取消勾選 RequiresHandle。

金幣在我的畫面上減少了,但其他人那裡沒有

購買是在 LocalScript 中完成的,所以只有你的裝置改變了。請像步驟 4 那樣,把扣除金幣與發放 Tool 移到伺服器 Script 中。

重新進入後購買的商品不見了

目前還沒有儲存任何東西。請見儲存購買。

用 RoCode 來做

如果不想手動組裝這一切,RoCode 可以在你開啟的場景中完成。它是獨立的程式設計 AI 代理:你在它的網頁聊天中描述功能,它的 Roblox Studio 外掛程式就會在你的 Explorer 中建立 Script、remote 與 GUI,所以不需要從聊天視窗複製程式碼。

你輸入

加入一個金幣商店:一個 Shop 按鈕,打開後是四種工具的格狀清單,價格以我 leaderstats 中的 Coins 計。伺服器要檢查價格,並把工具發到 Backpack 與 StarterGear。

RoCode 會做
  • 可以透過 Search Scripts 與 Read Script 瀏覽你的場景,找出已經有的 leaderstats 與商店程式碼,使用你的 Coins 數值,而不是再加第二個
  • 可以用 Build UI 組出視窗的骨架:商店版面附有佔位用的卡片,以及處理滑鼠移過效果與 Close 按鈕的 LocalScript;購買邏輯則另外用 Script 撰寫
  • 用 Create Instance 建立 RemoteFunction,並用 Create Script 撰寫目錄 ModuleScript、伺服器 Script 與 LocalScript
  • 在 Studio 中用 Check Script 檢查每個 Script 能否編譯(它不做型別檢查,也不執行 Script),每一批變更都是 Studio 中的一個復原點

通行證仍然要你自己在 Creator Hub 建立,因為 RoCode 無法建立通行證與 developer product,購買也要由你測試:使用外掛程式 3.9 或更新版本,RoCode 可以執行短暫的試玩測試並讀取錯誤;使用外掛程式 3.9.15 或更新版本,它的測試角色可以按 Shop 和 Buy 按鈕,但它只檢查自己決定要測試的項目。商店通常在核心玩法與儲存之後才做;用 RoCode 逐步製作遊戲的流程會告訴你它的位置。RoCode 如何連接 Studio。

常見問題

Roblox 的 Buy 按鈕該用 RemoteEvent 還是 RemoteFunction?

只要由伺服器檢查,兩者都可以。RemoteFunction 讓按鈕能等待伺服器的回覆並顯示出來,所以本教學使用它,Roblox 安全指南中的商店範例也是用 RemoteFunction。請只從用戶端呼叫它:呼叫 InvokeClient 的伺服器,如果用戶端一直不回覆,可能會永遠等下去。RemoteEvent 教學比較了這兩者。

要怎麼透過 NPC 而不是按鈕打開商店?

在 NPC 的某個零件中放一個 ProximityPrompt,例如它的 HumanoidRootPart,在伺服器 Script 中監聽它的 Triggered 事件,並傳送 RemoteEvent 給這位玩家,讓 LocalScript 顯示面板。如果只能在 NPC 附近購買,也要在 BuyItem 處理函式中檢查與 NPC 的距離,因為用戶端可以從任何地方呼叫 remote。

要怎麼販售可以買好幾次的商品?

對這類商品,略過「已經擁有」的檢查,並發放可以計數的東西而不是 Tool,例如替計算藥水數量的 IntValue 加 1。查價與檢查金幣的部分保持不變。

為什麼角色重生時商店會消失?

它的 ScreenGui 的 ResetOnSpawn 是 true,這是預設值,所以 Roblox 會在重生時刪除它。請像步驟 3 的 Script 那樣把它設為 false。

可以用免費的商店 GUI 範本嗎?

可以,任何版面都行,只要它的 Buy 按鈕只傳送商品 id,而購買本身在像 ShopService 這樣的伺服器 Script 中完成。使用範本前,先檢查它有沒有在 LocalScript 中扣金幣或發放商品。

來源與延伸閱讀

程式碼如何驗證:本頁每一段 Script 都通過 Luau 嚴格型別檢查,並使用 Roblox API 定義(luau-lsp,2026年11月20日)。型別檢查能找出拼錯的 API 與錯誤的型別,但無法檢查遊戲邏輯,所以發布前請先在 Studio 中測試。

在你自己的遊戲裡試試 RoCode。

每天都有免費點數,不需要信用卡。安裝外掛程式,描述你要的功能,再看看 Studio 裡出現了什麼。