要点
把物品和价格放在 ReplicatedStorage 里的 ModuleScript 中,用 ScreenGui、ScrollingFrame 和 UIGridLayout 搭出窗口,让每个 Buy 按钮调用 RemoteFunction,只传物品 id。接下来由 ServerScriptService 里的 Script 自己查找价格,检查并扣除玩家的 Coins,然后发放物品。
- 永远不要让客户端发送价格。任何人都可以用任意值调用你的 Remote,所以服务端从自己的目录副本里取价格。
- 买到的 Tool 要从 ServerStorage 克隆到玩家的 Backpack(马上就能用)和 StarterGear(重生后会回来)。
- 用 Robux 出售的东西是通行证和 developer product,由 MarketplaceService 处理。Roblox 还会为它们自动创建一个 Shop,它和金币商店不是一回事。
能用的商店是怎样构成的
在真正的游戏里能用的商店,分布在玩家设备和服务端两边。设备负责绘制窗口并说“我想买这把剑”。服务端是唯一可以信任的一方,由它决定这件事是否发生。那些“不好用”或被玩家用作弊破解的商店脚本,往往是在错误的一边做了这个决定。
| 部分 | 位置 | 作用 |
|---|---|---|
ModuleScript ShopCatalog | ReplicatedStorage | 物品 id、名称、价格,以及每件物品给出的 Tool。两边都会读取它。 |
RemoteFunction BuyItem | ReplicatedStorage 中的 ShopRemotes 文件夹 | 把购买请求送到服务端,再把回答带回来。 |
LocalScript ShopClient | StarterPlayerScripts | 搭建商店窗口,并在按下 Buy 按钮时发送物品 id。 |
Script ShopService | ServerScriptService | 检查请求,扣除 Coins 并发放 Tool。 |
| 你出售的 Tool | ServerStorage 中的 ShopItems 文件夹 | 服务端复制的原件。ServerStorage 中的任何东西都不会发送给玩家。 |
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 值。如果你做过 排行榜教程,你已经有了它,可以跳过这个脚本。否则在 ServerScriptService 中插入一个名为 Leaderstats 的 Script。它在开始时给每个人 200 金币,这样马上就能测试购买。
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 脚本。两个脚本各自创建 leaderstats 文件夹,会让每个玩家有两个文件夹,商店可能读到错的那个。
接下来创建脚本要查找的对象。名称区分大小写,所以请完全照这里的写法。
- 在 Explorer 中把鼠标移到 ReplicatedStorage 上,点击 + 按钮,插入一个名为
ShopRemotes的 Folder。在里面插入一个名为BuyItem的 RemoteFunction。 - 把鼠标移到 ServerStorage 上,插入一个名为
ShopItems的 Folder。 - 在 ShopItems 中为每件物品放一个 Tool,名称分别为
ClassicSword、Flashlight、GrappleHook和SpeedCoil。第一次测试时,Tool 里只要有一个名为Handle、未锚固的 Part 就够了。你已有的任何 Tool 也可以用:给它起对名字即可。真正能造成伤害的武器,可以按 剑的教程 或 枪的教程 来做;每篇都写了如何把它接到目录上。 - 选中每个 Tool,在 Properties 窗口中取消勾选 CanBeDropped。勾选时,按 Backspace 会把工具丢进 Workspace,任何玩家都能捡走买家付过钱的东西。
可以只从一个 Tool 开始。如果某件物品缺少 Tool,服务端会拒绝出售这件物品,并输出一条带它名称的警告,所以不会扣玩家任何东西。
第 2 步:目录中的物品和价格
目录是商店出售的所有东西的唯一列表。LocalScript 读取它来绘制卡片,服务端读取它来查找价格,所以改价格只需在一个地方改一处。
把鼠标移到 ReplicatedStorage 上,插入一个 ModuleScript,重命名为 ShopCatalog,并把内容替换为:
export type ShopItem = {
id: string, -- 之后会存进数据存储:玩家已经拥有这个物品后就不要再改
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 Attribute
function ShopCatalog.ownedAttribute(id: string): string
return "Owns_" .. id
end
return ShopCatalog
每件物品都有 id,以及另外用于显示的 name。玩家拥有某样东西时,服务端记录的是 id,所以之后可以给 "Classic Sword" 改名,而不会破坏已保存的购买。描述只是卡片上的文字;Tool 做什么由它自己的脚本决定。
玩家可以读取 ReplicatedStorage 中的 ModuleScript,所以这些价格是公开的。这没关系:卡片上本来就写着价格。重要的是客户端和服务端各自运行自己的模块副本,所以在自己设备上改了价格的玩家,并不会改变服务端的任何东西。
第 3 步:搭建商店 GUI
这个 LocalScript 用代码搭出整个窗口:Shop 按钮、带可滚动卡片网格的面板、目录中每件物品各一个 Buy 按钮、Coins 计数器,以及显示服务端回答的状态栏。既然全部由代码完成,粘贴后点击 Play 即可。如果你想手动布置窗口,后面的表格列出了每个对象。
- 在 Explorer 中展开 StarterPlayer,把鼠标移到 StarterPlayerScripts 上,插入一个名为
ShopClient的 LocalScript。 - 把它的内容替换为下面的代码。
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)
-- 购买成功时(或保存的物品加载完成时)服务端会设置这个 Attribute
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。游戏运行时它们不会改变任何东西。
| 对象 | 在商店中的作用 | 主要属性 |
|---|---|---|
ScreenGui | 存放屏幕上绘制的一切 | ResetOnSpawn 设为 false,让商店在重生后仍然存在 |
Frame | 窗口和每张物品卡片 | AnchorPoint 0.5, 0.5 和 Position 0.5, 0.5,让窗口居中 |
UISizeConstraint | 在大屏幕上限制窗口大小 | MaxSize 640 乘 460 |
ScrollingFrame | 卡片放不下时可以滚动 | CanvasSize 为 0,AutomaticCanvasSize 为 Y,让滚动区域随卡片增长 |
UIGridLayout | 把卡片排成行并换行 | CellSize 180 乘 200,CellPadding 12,SortOrder LayoutOrder |
UICorner | 圆角 | CornerRadius 8 到 14 像素 |
UIPadding | 内边距 | 每边 10 到 12 像素 |
TextButton | Shop、关闭和 Buy 按钮 | Activated 事件 |
如果你想手动绘制窗口,就在 StarterGui 中用这些属性搭出同样的对象,同样把 ScreenGui 的 ResetOnSpawn 设为 false,并保留一张卡片作为模板,由 LocalScript 为目录中的每件物品克隆。这样脚本只负责填充卡片和连接按钮。下一步的购买逻辑不变。
如果你的游戏从 主菜单 开始,那篇教程里有一行要加到 ShopClient 的代码,让 Shop 按钮只在玩家点击 Play 之后出现。要通过和商人对话来打开商店,NPC 对话教程 演示了如何添加 OpenShop 动作,让 ShopClient 打开窗口,而购买仍然经过商店的服务端检查。
第 4 步:在服务端检查和购买
这个 Script 是唯一能发生购买的地方。它接收物品 id,检查它,查找价格,检查玩家的 Coins,然后扣除金币并发放 Tool。它回答 Buy 按钮 true 或 false,外加一条用于显示的消息。
把鼠标移到 ServerScriptService 上,插入一个名为 ShopService 的 Script,粘贴以下内容:
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. 忽略双击和脚本发出的连串请求
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 的 Attribute,例如 Owns_sword。服务端设置的 Attribute 会复制到玩家设备上,所以 LocalScript 可以把卡片切换为 "Owned"。玩家在自己副本中做的修改不会传到服务端。
Tool 会进入两个地方。Backpack 中的副本会马上出现在快捷栏里。StarterGear 中的副本,Roblox 会在每次角色出现时放进新的 Backpack。没有它,买到的物品在玩家第一次死亡时就会消失。
为什么客户端永远不发送价格
玩家设备上的一切,这个玩家都能修改。作弊者在自己的游戏副本里运行自己的代码:他们可以读你的 LocalScript,修改 GUI,并以任意参数任意多次地调用 BuyItem:InvokeServer()。Roblox 的安全指南说要检查 Remote 收到的一切内容的类型和值,而它举的例子正好是一个商店。
| 作弊者发送 | 如果服务端相信了他 | ShopService 怎么做 |
|---|---|---|
| 价格 0 | 所有物品都免费 | 忽略它。价格取自目录。 |
| 价格 -1000 | Coins.Value -= -1000 反而给了他 1 000 金币 | 忽略它。 |
用 NaN 作为价格 | 任何与 NaN 的比较都为假,所以“金币不够”的检查永远不会触发 | 忽略它。 |
| 目录中没有的 id,或用表代替字符串 | 脚本出错,或卖出你本不打算出售的物品 | 回答 "That item does not exist." |
| 每秒几百个请求 | 服务器负载升高,检查中的任何漏洞都会被触发几百次 | 每个玩家每半秒最多处理一个请求。 |
| 在自己屏幕上修改过的 Coins | 用他并没有的金币购物 | 完全看不到这些。服务端只读取它自己的 Coins 值。 |
这条规则适用于你写的每一个 Remote:发送玩家选择了什么,例如物品 id 或格子编号,而永远不要发送它值多少钱或玩家应该得到什么。RemoteEvent 教程 更详细地讲解了 Remote 参数的检查。
第 5 步:测试商店
- 点击 Play。左边会出现 Shop 按钮。打开它并买下 Flashlight:Coins 减少 25,工具出现在快捷栏中,它的按钮变为 Owned。
- 试试价格为 300 的 Speed Coil。状态栏会写出还差多少金币,并且不会扣除任何东西。
- 通过游戏内菜单重置角色。由于 StarterGear 中有副本,Flashlight 会回到新的 Backpack 中。
- 测试时想给自己加金币,点击 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 接收,而不是你的脚本。
本教程有两条规则同样适用:在客户端用按钮发起购买窗口,只在服务端、在 Roblox 确认购买或玩家已经拥有通行证时发放权益。游戏通行证脚本教程 完整地搭建了这一切:进入时检查拥有状态、购买窗口、VIP 门之类的权益,以及什么时候用 developer product 代替通行证更好。定价时,免费的 Robux 抽成计算器 会显示通行证或 developer product 在扣除 Roblox 分成后能给你带来多少。
保存玩家的购买
我们做的一切只存在于一次会话中:在你用数据存储保存之前,玩家退出时金币和买到的物品都会被重置。为了不在这里重复保存代码,请参考 DataStore 教程(或 排行榜教程 的第 3 步,那里的版本更短),并记住商店的规则:
- 把物品的 id 保存起来,例如
{ "sword", "flashlight" },并和 Coins 值放在同一张表里,这样一次保存就同时写入花掉的金币和买到的物品。Tool 和其他实例无法放进数据存储。 - 数据加载完成后,遍历保存的 id,跳过目录中已不存在的,设置每个
Owns_Attribute,并像giveTool那样发放 Tool。商店窗口会自己更新,因为它在监听这些 Attribute。 - 通行证的拥有状态不需要保存:
UserOwnsGamePassAsync会在玩家每次进入时询问 Roblox。 - 永远不要保存数据没有加载成功的玩家,否则一次失败的加载可能会用空列表覆盖他的购买记录。
常见错误与解决办法
商店表现异常时,先检查这些。首先打开 Output 窗口(Window 菜单,然后 Output):脚本错误会写出脚本名和行号。
Infinite yield possible on 'ReplicatedStorage:WaitForChild("ShopRemotes")'
脚本在等待一个不存在于这个确切名称下的对象。检查 ShopRemotes、BuyItem、ShopCatalog 和 ShopItems 的拼写和大小写,并确认 ShopItems 在 ServerStorage 中,而不是在 ReplicatedStorage 中。脚本错误教程 详细讲解了这条警告。
Buy 按钮停在 "Buying..." 没有回应
服务端没有人设置 BuyItem.OnServerInvoke,所以 Roblox 会一直挂起请求,直到它被设置。确认 ShopService 是 Script 而不是 LocalScript,并且位于 ServerScriptService 中,再在 Output 中查找来自 ShopService 的 Infinite yield possible 警告:它表示脚本卡在等待 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 的零件,并且它的零件都不能锚固。如果工具不需要拿在手里,就改为取消勾选 RequiresHandle。
金币在我的屏幕上减少了,但别人看到的没变
购买发生在 LocalScript 中,所以只有你的设备改变了。像第 4 步那样,把扣金币和发放 Tool 移到服务端 Script 中。
重新进入后买到的物品消失了
目前还没有保存任何东西。见 保存购买。
用 RoCode 来做
如果不想手动搭建这一切,RoCode 可以在你打开的场景里完成。它是独立的写代码 AI 代理:你在它的网页聊天里描述功能,它的 Roblox Studio 插件就会在你的 Explorer 中创建脚本、Remote 和 GUI,所以不需要从聊天窗口复制代码。
添加一个金币商店:一个 Shop 按钮,打开一个由四个工具组成的网格,价格用我 leaderstats 中的 Coins 计。服务端要检查价格,并把工具发放到 Backpack 和 StarterGear。
- 可以用 Search Scripts 和 Read Script 查看你的场景,寻找已有的 leaderstats 和商店代码,从而使用你的 Coins 值,而不是再加一个
- 可以用 Build UI 搭出窗口的框架:商店布局带有占位卡片,以及负责悬停效果和 Close 按钮的 LocalScript;购买逻辑由单独的脚本编写
- 用 Create Instance 创建 RemoteFunction,用 Create Script 编写目录 ModuleScript、服务端 Script 和 LocalScript
- 用 Check Script 在 Studio 中检查每个脚本能否编译(它不检查类型,也不运行脚本),每批改动都是 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 步的脚本那样设为 false。
可以用免费的商店 GUI 模板吗?
可以,任何布局都行,只要它的 Buy 按钮只发送物品 id,而购买本身在类似 ShopService 的服务端 Script 中进行。用模板之前,检查它有没有在 LocalScript 里扣金币或发放物品。
参考资料
- Roblox Creator Docs: Securing the client-server boundary(英文). Remote 参数检查、NaN、频率限制和游戏内商店示例
- Roblox Creator Docs: Remote events and callbacks(英文). RemoteFunction、InvokeServer、OnServerInvoke 以及 InvokeClient 的风险
- Roblox Creator Docs: Passes(英文). 创建和出售通行证、UserOwnsGamePassAsync 和 PromptGamePassPurchaseFinished
- Roblox Creator Docs: Shop(英文). Roblox 自动创建的游戏内 Shop
- Roblox Creator Docs: Developer Products(英文). 可重复的 Robux 购买和 ProcessReceipt
- Roblox Creator Docs: StarterGear(英文). 为什么 StarterGear 中的 Tool 在重生后会回来
- Roblox Creator Docs: In-game tools(英文). Handle、锚固和 RequiresHandle
代码如何验证:本页的所有脚本都已用 Roblox API 类型定义(luau-lsp,2026年11月20日)通过 Luau strict 类型检查。类型检查能发现 API 名称写错和类型不匹配,但发现不了游戏逻辑上的错误。发布前请务必在 Studio 中测试。