教程 · 游戏系统

Roblox Studio 怎么做背包系统

背包看起来像是界面问题,但它能不能被破解、会不会丢物品,取决于物品存放在哪里。在这篇教程里,每个玩家的物品都放在服务端的一张表里,每个玩家收到一份副本并把它绘制成网格,通过服务端检查的请求来装备 Tool 和使用消耗品,所有内容都保存到数据存储中。

更新于 2026年11月20日阅读约 3 分钟作者

要点

把每个玩家的物品存放在服务端的一张表里,放在 ServerScriptService 中的 ModuleScript 内,并且只有这段代码可以添加、移除和堆叠物品。在 ReplicatedStorage 中的 ModuleScript 里把物品描述一次(id、名称、最大堆叠数)。每次修改后,服务端通过 RemoteEvent 给这个玩家发送他背包的副本,LocalScript 再用 ScrollingFrame 和 UIGridLayout 把它绘制成网格。

  • 客户端永远不会添加物品。它只能提出请求,例如 "装备我的剑",服务端会先确认玩家拥有它,再做任何事。
  • 物品只能通过你控制的服务端代码出现:拾取、经服务端检查的商店购买、奖励。
  • 在玩家离开时、服务器关闭时以及每隔几分钟,通过 DataStoreService 保存物品 id 和数量,而不是 Tool。永远不要保存数据没有加载成功的玩家。
本页内容
  1. 结构
  2. 为什么物品在服务端
  3. 1. 准备 Explorer
  4. 2. 物品目录
  5. 3. 服务端背包
  6. 4. 加载和保存
  7. 5. 拾取物品
  8. 6. 装备和使用
  9. 7. 网格界面
  10. 测试
  11. Common errors
  12. 用 RoCode
  13. 常见问题
  14. 参考资料

背包的结构

示意按 B,把鼠标悬停在物品上阅读说明,点击 Sword 把它拿在手里。

这个系统由六个小部分组成,每个部分只负责一件事。所有关于物品的规则都在一个服务端模块里,所以出问题时只需要在一个地方找。

系统的各个部分及其运行位置
部分类型和位置职责
ItemCatalogReplicatedStorage 中的 ModuleScript每种物品是什么:名称、说明、最大堆叠数,以及能否装备或使用。服务端和所有客户端都会读取它。
InventoryServiceServerScriptService 中的 ModuleScript保存所有玩家的格子。唯一会添加、移除和堆叠物品的代码。
InventoryDataServerScriptService 中的 Script玩家进入时加载他的物品,并负责保存。
InventoryActionsServerScriptService 中的 Script检查并执行装备和使用的请求。
ItemPickupPart 内的 Script把物品发给捡起它的人。
InventoryClientStarterPlayerScripts 中的 LocalScript绘制网格并发送请求。自己不修改任何东西。

数据只朝一个方向流动。服务端修改背包,然后把整个背包通过 InventoryUpdated 发给这个玩家,客户端重新绘制。玩家点击格子时,客户端发送带物品 id 的 EquipItem 或 UseItem;服务端检查请求,做出修改,新的副本沿同样的路径发回来。发送整个背包比发送变化更简单,而对于几十个格子来说,消息仍然很小。

为什么客户端永远不添加物品

人们很想直接在显示物品的 LocalScript 里添加物品:玩家一点击,格子就填上了。这会以两种方式出问题。

  • 别人都看不到。LocalScript 中的修改只存在于这个玩家的设备上。服务端不知道它,所以它不会被保存,任何服务端脚本也无法使用它。
  • 谁都能伪造。如果用 AddItem(itemId, amount) 这样的 Remote 来补救,作弊者就能自己调用这个事件,传任意参数,调用任意多次。Roblox 的安全指南说,服务端必须先检查客户端发来的一切,再使用它。

所以在这篇教程里,客户端只能请求对玩家已经拥有的物品做些什么:"装备这个" 和 "使用这个"。每个请求只有一个物品 id,没有数量,并在服务端经过同一套检查:它是字符串、这种物品存在、玩家至少有一个,并且玩家每秒发送的请求不超过四个。然后服务端自己根据目录找到 Tool。它从不接受客户端发来的 Tool、路径或实例,这也是同一份指南提醒过的。

物品只能通过服务端代码进入背包:经服务端检查的拾取、服务端已扣款的购买(由 商店教程 搭建)、任务奖励或掉落。关于 Remote 的总体用法,以及如何检查其他类型的参数,请阅读 RemoteEvent 教程。

第 1 步:准备 Explorer

手动创建这些对象。后面步骤中的脚本会按名字查找它们,所以每个名字都要和这里写得一模一样。

  1. 在 ReplicatedStorage 中插入一个名为 InventoryRemotes 的 Folder。在里面插入三个 RemoteEvent,分别命名为 InventoryUpdated、EquipItem 和 UseItem。
  2. 在 ServerStorage 中插入一个名为 ItemTools 的 Folder。在里面插入一个名为 Sword 的 Tool,再在 Tool 里插入一个名为 Handle 的 Part(1 x 4 x 1 格就可以)。确认 Handle 没有勾选 Anchored:Roblox 提醒,角色拿着带锚固零件的工具时会被卡在原地。你已有的 Tool 也可以用,只要它的名字与第 2 步中的目录一致。
  3. 随着步骤推进添加脚本。层级树显示了每个脚本的位置。
完成本教程后的 Explorer
ReplicatedStorage
  ItemCatalog ModuleScript new
  InventoryRemotes Folder new
    InventoryUpdated RemoteEvent new
    EquipItem RemoteEvent new
    UseItem RemoteEvent new
ServerScriptService
  InventoryService ModuleScript new
  InventoryData Script new
  InventoryActions Script new
ServerStorage
  ItemTools Folder new
    Sword Tool new
      Handle Part new
StarterPlayer
  StarterPlayerScripts
    InventoryClient LocalScript new
Workspace
  Apple Part new
    ItemPickup Script new

第 2 步:在目录中描述物品

目录把每一种可能存在的物品描述一次。之后背包里只保存物品 id 和数量。这样存档会很小,以后也可以重命名物品或改写它的说明,而不会动到任何人保存的数据。

在 ReplicatedStorage 中插入一个 ModuleScript,命名为 ItemCatalog,并把它的内容替换为:

ModuleScript 位置: ReplicatedStorage 名称: ItemCatalog
-- 游戏里可能存在的所有物品。服务端和所有客户端都会读取这份列表;
-- 只有服务端决定谁拥有什么。
export type Item = {
	id: string, -- 必须与下面的键一致
	name: string,
	description: string,
	maxStack: number, -- 这种物品在一个格子里最多能放多少
	icon: string?, -- 可选的图片:"rbxassetid://" 加上你的图片 ID
	toolName: string?, -- ServerStorage.ItemTools 中的 Tool:物品可以装备
	heal: number?, -- 恢复多少生命值:物品是消耗品
}

local items: { [string]: Item } = {
	sword = {
		id = "sword",
		name = "Sword",
		description = "Equip it to put it in your hand.",
		maxStack = 1,
		toolName = "Sword",
	},
	apple = {
		id = "apple",
		name = "Apple",
		description = "Use it to restore 25 health.",
		maxStack = 10,
		heal = 25,
	},
	wood = {
		id = "wood",
		name = "Wood",
		description = "A building material.",
		maxStack = 50,
	},
}

local ItemCatalog = {}

-- 返回这个 id 对应的物品,如果没有这种物品则返回 nil
function ItemCatalog.get(id: string): Item?
	return items[id]
end

return ItemCatalog

可选字段决定物品能做什么。toolName 让它可以装备,heal 让它可以使用,而两个字段都没有的物品(比如木头)会一直留在背包里,直到其他服务端代码把它移除(合成、出售)。

要添加物品,就添加一项键与 id 一致的记录。id 区分大小写,而且保存的正是 id,所以当玩家已经拥有某个物品时,永远不要修改它的 id:请修改它的 name。

第 3 步:在服务端保存背包

这个 ModuleScript 掌管每个玩家的背包。每个背包是一个格子列表,每个格子里有物品 id 和数量,另外还有 20 个格子的容量。其他服务端脚本调用它的函数,除此之外没有任何代码修改这张表。

在 ServerScriptService 中插入一个 ModuleScript,命名为 InventoryService:

ModuleScript 位置: ServerScriptService 名称: InventoryService
-- 唯一会修改背包的代码。它放在 ServerScriptService 中,
-- 客户端既看不到它,也无法运行它。
local ReplicatedStorage = game:GetService("ReplicatedStorage")

-- Strict 模式看不出通过 WaitForChild 进行的 require 返回什么,所以
-- 我们描述这个脚本用到的那部分模块
type Item = { id: string, maxStack: number }
type Catalog = { get: (id: string) -> Item? }
local ItemCatalog = require(ReplicatedStorage:WaitForChild("ItemCatalog")) :: Catalog

local remotes = ReplicatedStorage:WaitForChild("InventoryRemotes")
local inventoryUpdated = remotes:WaitForChild("InventoryUpdated") :: RemoteEvent

export type Slot = { id: string, count: number }
type Inventory = { slots: { Slot }, capacity: number, equipped: string? }

local CAPACITY = 20 -- 每名玩家的格子数
local STARTER_ITEMS: { Slot } = { -- 全新玩家开局时拥有的物品
	{ id = "sword", count = 1 },
	{ id = "apple", count = 3 },
}

local inventories: { [Player]: Inventory } = {}

local InventoryService = {}

-- 把背包的副本发送给它的主人。每次修改后都会调用。
local function sync(player: Player)
	local inventory = inventories[player]
	if inventory then
		inventoryUpdated:FireClient(player, {
			capacity = inventory.capacity,
			slots = inventory.slots,
			equipped = inventory.equipped,
		})
	end
end

-- 堆叠规则:先填满未满的堆叠,再在空格子里
-- 开始新的堆叠。返回实际添加的数量,可能少于请求的数量。
local function addToInventory(inventory: Inventory, item: Item, amount: number): number
	local remaining = amount
	for _, slot in inventory.slots do
		if remaining == 0 then
			break
		end
		if slot.id == item.id and slot.count < item.maxStack then
			local moved = math.min(item.maxStack - slot.count, remaining)
			slot.count += moved
			remaining -= moved
		end
	end
	while remaining > 0 and #inventory.slots < inventory.capacity do
		local moved = math.min(item.maxStack, remaining)
		table.insert(inventory.slots, { id = item.id, count = moved })
		remaining -= moved
	end
	return amount - remaining
end

function InventoryService.count(player: Player, itemId: string): number
	local inventory = inventories[player]
	local total = 0
	if inventory then
		for _, slot in inventory.slots do
			if slot.id == itemId then
				total += slot.count
			end
		end
	end
	return total
end

-- 这种物品还能放下多少:它的堆叠里的剩余空间加上空格子
function InventoryService.spaceFor(player: Player, itemId: string): number
	local inventory = inventories[player]
	local item = ItemCatalog.get(itemId)
	if not inventory or not item then
		return 0
	end
	local space = (inventory.capacity - #inventory.slots) * item.maxStack
	for _, slot in inventory.slots do
		if slot.id == itemId then
			space += item.maxStack - slot.count
		end
	end
	return space
end

-- 最多添加 amount 个物品。返回实际添加的数量(如果物品不存在、
-- 背包已满或尚未加载完成,则为 0)。
function InventoryService.add(player: Player, itemId: string, amount: number): number
	local inventory = inventories[player]
	local item = ItemCatalog.get(itemId)
	local wanted = math.floor(amount)
	if not inventory or not item or wanted < 1 then
		return 0
	end
	local added = addToInventory(inventory, item, wanted)
	if added > 0 then
		sync(player)
	end
	return added
end

-- 从最后的堆叠开始,正好移除 amount 个物品。
-- 如果玩家拥有的数量不够,则什么都不移除并返回 false。
function InventoryService.remove(player: Player, itemId: string, amount: number): boolean
	local inventory = inventories[player]
	local wanted = math.floor(amount)
	if not inventory or wanted < 1 or InventoryService.count(player, itemId) < wanted then
		return false
	end
	local remaining = wanted
	-- 从末尾往前遍历,这样 table.remove 不会跳过格子
	for index = #inventory.slots, 1, -1 do
		local slot = inventory.slots[index]
		if slot.id == itemId then
			local taken = math.min(slot.count, remaining)
			slot.count -= taken
			remaining -= taken
			if slot.count == 0 then
				table.remove(inventory.slots, index)
			end
			if remaining == 0 then
				break
			end
		end
	end
	sync(player)
	return true
end

function InventoryService.getEquipped(player: Player): string?
	local inventory = inventories[player]
	return if inventory then inventory.equipped else nil
end

function InventoryService.setEquipped(player: Player, itemId: string?)
	local inventory = inventories[player]
	if inventory then
		inventory.equipped = itemId
		sync(player)
	end
end

-- 玩家的存档数据加载完成时调用。saved 是数据存储
-- 返回的内容:新玩家为 nil。每一项都会重新经过
-- 堆叠规则,所以已删除的物品和旧的堆叠上限不会造成问题。
function InventoryService.load(player: Player, saved: any)
	local inventory: Inventory = { slots = {}, capacity = CAPACITY }
	local entries: { Slot } = STARTER_ITEMS
	if type(saved) == "table" and type(saved.slots) == "table" then
		entries = {}
		for _, entry in saved.slots do
			if type(entry) == "table" and type(entry.id) == "string" and type(entry.count) == "number" then
				table.insert(entries, { id = entry.id, count = math.floor(entry.count) })
			end
		end
	end
	for _, entry in entries do
		local item = ItemCatalog.get(entry.id)
		if item and entry.count > 0 then
			addToInventory(inventory, item, entry.count)
		end
	end
	inventories[player] = inventory
	sync(player)
end

-- 用于保存的简单副本;如果玩家数据始终没有加载成功,则为 nil
function InventoryService.serialize(player: Player): { version: number, slots: { Slot } }?
	local inventory = inventories[player]
	if not inventory then
		return nil
	end
	local slots: { Slot } = {}
	for index, slot in inventory.slots do
		slots[index] = { id = slot.id, count = slot.count }
	end
	return { version = 1, slots = slots }
end

function InventoryService.unload(player: Player)
	inventories[player] = nil
end

return InventoryService

type 行以及 require 之后的 :: 类型转换只是给 Luau 类型检查器看的,它看不出通过 WaitForChild 找到的模块返回什么。游戏运行时它们不会改变任何东西。本教程中的其他脚本也是这样做的。

以上面的目录为例(苹果最多堆叠到 10 个),堆叠规则是这样运作的:

  • 给一个有 7 个苹果堆叠的玩家添加 15 个苹果,这个堆叠会被填满到 10 个,然后开始一个 5 个的新堆叠。
  • 格子用完时,add 会添加能放下的部分,并返回这个数字。需要全部放下否则就一个都不放时,请先调用 spaceFor,就像第 5 步中的拾取那样。
  • remove 按全有或全无的原则工作。向只有 2 个苹果的玩家请求 3 个苹果,不会移除任何东西,并返回 false,所以在给出任何回报之前请先检查结果。
  • 格子之间没有空洞:一个格子空了,后面的格子会往前移。这样列表更容易发送和保存。关于保持固定位置的格子,见文末的常见问题。
其他服务端脚本可以调用什么
函数返回值用途
add(player, itemId, amount)实际添加的数量拾取、奖励、购买
remove(player, itemId, amount)全部移除时为 true使用、出售、合成
count(player, itemId)所有堆叠的总数检查玩家拥有什么
spaceFor(player, itemId)还能放下多少按全有或全无原则添加之前的检查
getEquipped、setEquipped已装备物品的 id 或 nil装备,见第 6 步
load、serialize、unload可直接保存的副本(serialize)加载和保存,见第 4 步

第 4 步:加载并保存每个背包

背包存在于服务器内存中,所以玩家离开时就会消失。这个脚本在玩家进入时从数据存储加载他的格子,并在他离开时、服务器关闭时,以及为防服务器崩溃每隔三分钟,把它们写回去。它只保存物品 id 和数量:数据存储无法保存 Tool 这样的 Instance。

在 ServerScriptService 中插入一个 Script,命名为 InventoryData:

Script 位置: ServerScriptService 名称: InventoryData
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local RunService = game:GetService("RunService")
local ServerScriptService = game:GetService("ServerScriptService")

type InventoryApi = {
	load: (player: Player, saved: any) -> (),
	serialize: (player: Player) -> any,
	unload: (player: Player) -> (),
}
local InventoryService = require(ServerScriptService:WaitForChild("InventoryService")) :: InventoryApi

local STORE_NAME = "PlayerInventory_v1"
local LOAD_ATTEMPTS = 3
local AUTOSAVE_SECONDS = 180

-- 只保存数据已加载的玩家。加载失败后
-- 绝不能保存,否则空背包会覆盖真正的背包。
local canSave: { [Player]: boolean } = {}
local activeSaves = 0

local function keyFor(player: Player): string
	return "User_" .. player.UserId
end

-- 一次失败的请求不应该让任何人丢失物品,所以会尝试几次。
-- GetDataStore 也放在 pcall 里,所以没有数据存储访问权限的
-- Studio 会话只会收到警告,而不会让这个脚本停下来。
local function loadSaved(player: Player): (boolean, any)
	for attempt = 1, LOAD_ATTEMPTS do
		local ok, result = pcall(function()
			return DataStoreService:GetDataStore(STORE_NAME):GetAsync(keyFor(player))
		end)
		if ok then
			return true, result
		end
		warn(`Inventory load failed for {player.Name} (attempt {attempt}): {result}`)
		if attempt < LOAD_ATTEMPTS then
			task.wait(attempt * 2)
		end
	end
	return false, nil
end

local function onPlayerAdded(player: Player)
	local ok, saved = loadSaved(player)
	if player.Parent ~= Players then
		return -- 玩家在我们加载时离开了
	end
	if ok then
		InventoryService.load(player, saved) -- 新玩家的 saved 为 nil
		canSave[player] = true
	elseif RunService:IsStudio() then
		-- 通常意味着 Studio 对 API services 的访问已关闭。使用
		-- 初始物品进行游戏,以便可以测试,但绝不保存它们。
		warn("Inventory not loaded: playing with starter items that will not be saved")
		InventoryService.load(player, nil)
	else
		player:Kick("Your inventory could not be loaded. Please rejoin in a minute.")
	end
end

local function save(player: Player)
	if not canSave[player] then
		return -- 数据始终没有加载成功,没有可以安全写入的内容
	end
	local data = InventoryService.serialize(player)
	if not data then
		return
	end
	activeSaves += 1
	local ok, err = pcall(function()
		DataStoreService:GetDataStore(STORE_NAME):SetAsync(keyFor(player), data, { player.UserId })
	end)
	activeSaves -= 1
	if not ok then
		warn(`Inventory save failed for {player.Name}: {err}`)
	end
end

Players.PlayerAdded:Connect(onPlayerAdded)
for _, player in Players:GetPlayers() do
	task.spawn(onPlayerAdded, player)
end

Players.PlayerRemoving:Connect(function(player: Player)
	save(player)
	canSave[player] = nil
	InventoryService.unload(player)
end)

-- 服务器关闭时,保存所有还在的玩家,并等待每一个
-- 正在进行的保存,包括由 PlayerRemoving 发起的保存
game:BindToClose(function()
	for _, player in Players:GetPlayers() do
		task.spawn(save, player)
	end
	while activeSaves > 0 do
		task.wait()
	end
end)

-- 每隔几分钟保存一次所有人,这样服务器崩溃只会损失几分钟,而不是整场游戏
while true do
	task.wait(AUTOSAVE_SECONDS)
	for _, player in Players:GetPlayers() do
		task.spawn(save, player)
	end
end

这个脚本做了什么,以及为什么:

  • 带默认值的加载。新玩家没有保存的值,所以 GetAsync 返回 nil,他会得到初始物品。保存的格子会重新经过堆叠规则,所以从目录中删除的物品或调小的最大堆叠数都不会破坏加载。放不下的内容,或者 id 已不在目录中的内容会被丢弃,下一次保存会让这成为永久结果,所以请把玩家可能拥有的每个 id 都保留在目录中。
  • 加载失败后绝不保存。只有 canSave 中的玩家会被写入。在正式服务器上,重试三次后数据仍未加载的玩家会被要求重新加入。在 Studio 中,他会改为得到不会被保存的初始物品,并因为重试而晚几秒出现。在场景发布并开启 API 访问之前,一直都会是这样。
  • 离开时和关闭时保存。BindToClose 会保存所有还在服务器上的玩家,并等待正在进行的保存。Roblox 给绑定的函数最多 30 秒。
  • 不超出限额。每名玩家每三分钟写入一次,离开时再写入一次,远低于服务器的标准预算:每分钟 60 次写入,外加每名玩家 40 次(依据 2026 年 9 月 30 日的文档)。键模板 User_ 来自 Roblox 的建议,而把 user ID 传给 SetAsync 会把数据和这个玩家关联起来,Roblox 强烈建议这样做,以便处理数据删除请求。

对于小型游戏,这是一个可靠的基础。会话锁(防止快速换服的玩家在旧服务器保存之前就加载数据),以及何时用 UpdateAsync 代替 SetAsync,请参阅 DataStore 教程。

第 5 步:从世界中发放物品

拾取是让物品进入背包最简单的方式:一个带 ProximityPrompt 的零件,玩家使用它时添加物品。脚本在服务端监听它的 Triggered 事件,所以物品是在客户端无法插手的地方添加的。

  1. 在 Workspace 中添加一个 Part,命名为 Apple,涂成红色。开启 Anchored,关闭 CanCollide,这样它隐身时不会有人撞上它。提示会显示零件的名字。
  2. 选中这个零件,把 Properties 窗口滚动到 Attributes 部分,点击 +。添加 string 类型的 ItemId 并点击 Save,然后把值设为 apple。用同样的方法添加 number 类型的 Amount,值为 1。
  3. 在零件里插入一个 Script,命名为 ItemPickup,粘贴这段代码:
Script 位置: Workspace 中的零件 Apple 名称: ItemPickup
-- 把这个 Script 放进一个 Part,并给 Part 两个 Attribute:
-- ItemId(字符串,例如 apple)和 Amount(数字,例如 1)。
local ServerScriptService = game:GetService("ServerScriptService")

type InventoryApi = {
	add: (player: Player, itemId: string, amount: number) -> number,
	spaceFor: (player: Player, itemId: string) -> number,
}
local InventoryService = require(ServerScriptService:WaitForChild("InventoryService")) :: InventoryApi

local part = script.Parent :: BasePart
local RESPAWN_SECONDS = 15

local itemId = part:GetAttribute("ItemId")
local amount = part:GetAttribute("Amount")
if typeof(itemId) ~= "string" or typeof(amount) ~= "number" or amount < 1 then
	error(`{part:GetFullName()} needs an ItemId (string) and an Amount (number, 1 or more) attribute`)
end

local prompt = Instance.new("ProximityPrompt")
prompt.ActionText = "Pick up"
prompt.ObjectText = part.Name
prompt.Parent = part

local visibleTransparency = part.Transparency

prompt.Triggered:Connect(function(player: Player)
	if not prompt.Enabled then
		return -- 刚刚被别人捡走了
	end
	-- 在服务端检查距离,而不是相信请求
	local character = player.Character
	if not character then
		return
	end
	local distance = (character:GetPivot().Position - part.Position).Magnitude
	if distance > prompt.MaxActivationDistance + 5 then
		return
	end
	if InventoryService.spaceFor(player, itemId) < amount then
		return -- 空间不够:把物品留在原地
	end
	InventoryService.add(player, itemId, amount)

	prompt.Enabled = false
	part.Transparency = 1
	task.wait(RESPAWN_SECONDS)
	part.Transparency = visibleTransparency
	prompt.Enabled = true
end)

复制这个零件就能摆放更多物品。修改 Attribute,就能发放木头、另一把剑或一堆苹果。

Roblox 会为 Triggered 检查距离,但它的安全指南仍然要求在服务端检查提示:即使 Enabled 为 false,作弊者也能触发提示的事件,还能把未锚固的零件拉到自己的角色身边。所以脚本自己检查 Enabled 和距离,零件也因此是锚固的。

任何其他服务端脚本都以同样的方式发放物品。在购买、任务或击杀之后,像上面的脚本那样通过 require 引入 InventoryService,并调用 InventoryService.add(player, "wood", 5)。物品不能丢失时,请先检查 spaceFor。NPC 也可以是一个来源:在 NPC 对话教程 中,一个回答会在服务端触发一个动作,这个动作同样可以调用 InventoryService.add。

第 6 步:装备 Tool 和使用物品

两个 RemoteEvent 承载了客户端唯一能发出的请求。EquipItem 把物品 Tool 的一份副本从 ServerStorage 放进玩家的 Backpack(屏幕底部的快捷栏)和他的手中,再次请求会把它收起。UseItem 移除一个可使用的物品并施加它的效果,这里是治疗。

在 ServerScriptService 中插入一个 Script,命名为 InventoryActions:

Script 位置: ServerScriptService 名称: InventoryActions
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerScriptService = game:GetService("ServerScriptService")
local ServerStorage = game:GetService("ServerStorage")

type Item = { id: string, toolName: string?, heal: number? }
type Catalog = { get: (id: string) -> Item? }
type InventoryApi = {
	count: (player: Player, itemId: string) -> number,
	remove: (player: Player, itemId: string, amount: number) -> boolean,
	getEquipped: (player: Player) -> string?,
	setEquipped: (player: Player, itemId: string?) -> (),
}
local ItemCatalog = require(ReplicatedStorage:WaitForChild("ItemCatalog")) :: Catalog
local InventoryService = require(ServerScriptService:WaitForChild("InventoryService")) :: InventoryApi

local remotes = ReplicatedStorage:WaitForChild("InventoryRemotes")
local equipItem = remotes:WaitForChild("EquipItem") :: RemoteEvent
local useItem = remotes:WaitForChild("UseItem") :: RemoteEvent
local itemTools = ServerStorage:WaitForChild("ItemTools")

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

-- 每个请求都从这里开始。客户端可以在任何时候发送任何东西,所以
-- 要检查类型、物品是否存在、玩家是否拥有它,以及请求频率。
local function ownedItem(player: Player, itemId: unknown): Item?
	if typeof(itemId) ~= "string" then
		return nil
	end
	local now = os.clock()
	if now - (lastRequest[player] or 0) < COOLDOWN_SECONDS then
		return nil
	end
	lastRequest[player] = now
	local item = ItemCatalog.get(itemId)
	if not item or InventoryService.count(player, itemId) < 1 then
		return nil
	end
	return item
end

-- 销毁这个物品的 Tool,无论副本在哪里:快捷栏、手中或 StarterGear
local function destroyTools(container: Instance?, itemId: string)
	if not container then
		return
	end
	for _, child in container:GetChildren() do
		if child:IsA("Tool") and child:GetAttribute("InventoryItem") == itemId then
			child:Destroy()
		end
	end
end

local function unequip(player: Player)
	local equippedId = InventoryService.getEquipped(player)
	if equippedId then
		destroyTools(player:FindFirstChildOfClass("Backpack"), equippedId)
		destroyTools(player.Character, equippedId)
		destroyTools(player:FindFirstChildOfClass("StarterGear"), equippedId)
		InventoryService.setEquipped(player, nil)
	end
end

local function equip(player: Player, item: Item, toolName: string)
	local template = itemTools:FindFirstChild(toolName)
	local backpack = player:FindFirstChildOfClass("Backpack")
	if not template or not template:IsA("Tool") or not backpack then
		warn(`Cannot equip {item.id}: no Tool named {toolName} in ServerStorage.ItemTools`)
		return
	end
	unequip(player) -- 一次只装备一个工具

	local tool = template:Clone()
	tool.CanBeDropped = false -- 被丢下的副本可能被别人捡走
	tool:SetAttribute("InventoryItem", item.id)
	tool.Parent = backpack

	-- StarterGear 中的第二份副本会在重生后复制回 Backpack
	local starterGear = player:FindFirstChildOfClass("StarterGear")
	if starterGear then
		local gearCopy = tool:Clone()
		gearCopy.Parent = starterGear
	end

	local character = player.Character
	local humanoid = character and character:FindFirstChildOfClass("Humanoid")
	if humanoid and humanoid.Health > 0 then
		humanoid:EquipTool(tool) -- 直接拿到手里
	end
	InventoryService.setEquipped(player, item.id)
end

equipItem.OnServerEvent:Connect(function(player: Player, itemId: unknown)
	local item = ownedItem(player, itemId)
	if not item or not item.toolName then
		return
	end
	if InventoryService.getEquipped(player) == item.id then
		unequip(player) -- 再次点击已装备的物品会卸下它
	else
		equip(player, item, item.toolName)
	end
end)

useItem.OnServerEvent:Connect(function(player: Player, itemId: unknown)
	local item = ownedItem(player, itemId)
	if not item or not item.heal then
		return
	end
	local heal = item.heal
	local character = player.Character
	local humanoid = character and character:FindFirstChildOfClass("Humanoid")
	if not humanoid or humanoid.Health <= 0 or humanoid.Health >= humanoid.MaxHealth then
		return -- 已死亡或生命值已满:不消耗物品
	end
	-- 先拿走物品,只有成功后才治疗
	if InventoryService.remove(player, item.id, 1) then
		humanoid.Health = math.min(humanoid.MaxHealth, humanoid.Health + heal)
	end
end)

Players.PlayerRemoving:Connect(function(player: Player)
	lastRequest[player] = nil
end)
每种请求允许做什么
请求客户端发送服务端在执行前检查
EquipItem物品 id它是字符串,物品存在,玩家拥有它,请求频率不超过每秒四次,物品有 toolName,并且 ServerStorage.ItemTools 中有同名的 Tool
UseItem物品 id同样的类型、拥有和频率检查,物品有 heal 值,角色活着且受了伤,并且在增加生命值之前先移除一个物品

有三个细节防止 Tool 被复制或丢失。副本的 CanBeDropped 为 false,因为丢下的 Tool 会掉进 Workspace,别的玩家可以捡走,而原物品还留在背包里。每份副本都带有 InventoryItem Attribute,所以卸下时可以找到并销毁每一份副本,无论它在哪里。如果玩家有 StarterGear 容器,会在里面放第二份副本。Roblox 在每次角色出现时把 StarterGear 复制到 Backpack,所以已装备的剑在重生后会回来。

一次只能装备一个 Tool,而且装备状态不会被保存,所以玩家重新加入后快捷栏是空的。如果以后添加出售或丢弃功能,请在物品的最后一份离开背包之前先把它卸下。

占位用的剑可以换成真的能战斗的剑:按 剑教程 做一个 Tool,保留 Sword 这个名字,并用它替换 ItemTools 里的占位剑。无论玩家是怎么得到剑的,那篇教程中的服务端脚本都会检查每一次攻击。

第 7 步:绘制背包网格

LocalScript 用代码构建整个窗口,所以不需要手动摆放任何东西。ScrollingFrame 容纳格子,里面的 UIGridLayout 把它们排成行,AutomaticCanvasSize 会随着行数增加扩大可滚动区域。

在 Explorer 中展开 StarterPlayer,在 StarterPlayerScripts 中插入一个 LocalScript,命名为 InventoryClient:

LocalScript 位置: StarterPlayerScripts 名称: InventoryClient
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UserInputService = game:GetService("UserInputService")

type Item = { name: string, description: string, icon: string?, toolName: string?, heal: number? }
type Catalog = { get: (id: string) -> Item? }
type Slot = { id: string, count: number }
type Snapshot = { capacity: number, slots: { Slot }, equipped: string? }

local ItemCatalog = require(ReplicatedStorage:WaitForChild("ItemCatalog")) :: Catalog
local remotes = ReplicatedStorage:WaitForChild("InventoryRemotes")
local inventoryUpdated = remotes:WaitForChild("InventoryUpdated") :: RemoteEvent
local equipItem = remotes:WaitForChild("EquipItem") :: RemoteEvent
local useItem = remotes:WaitForChild("UseItem") :: RemoteEvent

local player = Players.LocalPlayer
local TOGGLE_KEY = Enum.KeyCode.B

local COLOURS = {
	panel = Color3.fromRGB(24, 20, 36),
	slot = Color3.fromRGB(44, 38, 64),
	empty = Color3.fromRGB(34, 30, 48),
	equipped = Color3.fromRGB(124, 77, 255),
	text = Color3.fromRGB(240, 238, 245),
	muted = Color3.fromRGB(170, 165, 185),
}

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

local function makeLabel(parent: GuiObject, text: string, textSize: number): TextLabel
	local label = Instance.new("TextLabel")
	label.BackgroundTransparency = 1
	label.Font = Enum.Font.BuilderSansBold
	label.TextColor3 = COLOURS.text
	label.TextSize = textSize
	label.Text = text
	label.Parent = parent
	return label
end

-- 1. 只构建一次窗口。ResetOnSpawn = false 让它在重生后保留。
local gui = Instance.new("ScreenGui")
gui.Name = "InventoryGui"
gui.ResetOnSpawn = false
gui.Parent = player:WaitForChild("PlayerGui")

local openButton = Instance.new("TextButton")
openButton.AnchorPoint = Vector2.new(0, 0.5)
openButton.Position = UDim2.new(0, 16, 0.5, 0)
openButton.Size = UDim2.fromOffset(140, 40)
openButton.BackgroundColor3 = COLOURS.panel
openButton.Font = Enum.Font.BuilderSansBold
openButton.TextColor3 = COLOURS.text
openButton.TextSize = 18
openButton.Text = "Inventory (B)"
addCorner(openButton, 8)
openButton.Parent = gui

local panel = Instance.new("Frame")
panel.AnchorPoint = Vector2.new(0.5, 0.5)
panel.Position = UDim2.fromScale(0.5, 0.5)
panel.Size = UDim2.fromScale(0.9, 0.8)
panel.BackgroundColor3 = COLOURS.panel
panel.Visible = false
addCorner(panel, 12)
panel.Parent = gui

local sizeLimit = Instance.new("UISizeConstraint")
sizeLimit.MaxSize = Vector2.new(440, 400)
sizeLimit.Parent = panel

local title = makeLabel(panel, "Inventory", 22)
title.Position = UDim2.fromOffset(16, 8)
title.Size = UDim2.new(1, -32, 0, 32)
title.TextXAlignment = Enum.TextXAlignment.Left

local slotCount = makeLabel(panel, "", 16)
slotCount.Position = UDim2.fromOffset(16, 8)
slotCount.Size = UDim2.new(1, -32, 0, 32)
slotCount.TextColor3 = COLOURS.muted
slotCount.TextXAlignment = Enum.TextXAlignment.Right

local grid = Instance.new("ScrollingFrame")
grid.Position = UDim2.fromOffset(12, 48)
grid.Size = UDim2.new(1, -24, 1, -100)
grid.BackgroundTransparency = 1
grid.BorderSizePixel = 0
grid.CanvasSize = UDim2.new() -- AutomaticCanvasSize 会按格子数量扩大它
grid.AutomaticCanvasSize = Enum.AutomaticSize.Y
grid.ScrollingDirection = Enum.ScrollingDirection.Y
grid.ScrollBarThickness = 6
grid.Parent = panel

local layout = Instance.new("UIGridLayout")
layout.CellSize = UDim2.fromOffset(72, 72)
layout.CellPadding = UDim2.fromOffset(8, 8)
layout.SortOrder = Enum.SortOrder.LayoutOrder
layout.Parent = grid

local info = makeLabel(panel, "Click an item to equip or use it.", 16)
info.AnchorPoint = Vector2.new(0, 1)
info.Position = UDim2.new(0, 16, 1, -8)
info.Size = UDim2.new(1, -32, 0, 40)
info.Font = Enum.Font.BuilderSans
info.TextColor3 = COLOURS.muted
info.TextWrapped = true
info.TextXAlignment = Enum.TextXAlignment.Left

-- 2. 每个格子一个单元格。这里只绘制服务端发来的内容;
-- 背包本身永远不会在这里被修改。
local function makeCell(index: number, slot: Slot?, equippedId: string?)
	local cell = Instance.new("TextButton")
	cell.LayoutOrder = index
	cell.Text = ""
	cell.AutoButtonColor = slot ~= nil
	cell.BackgroundColor3 = if slot then COLOURS.slot else COLOURS.empty
	addCorner(cell, 8)
	cell.Parent = grid
	if not slot then
		return -- 空格子
	end

	local itemId = slot.id
	local item = ItemCatalog.get(itemId)
	local name = if item then item.name else itemId

	if item and item.icon then
		local image = Instance.new("ImageLabel")
		image.BackgroundTransparency = 1
		image.Size = UDim2.fromScale(1, 1)
		image.Image = item.icon
		image.Parent = cell
	else
		local nameLabel = makeLabel(cell, name, 14)
		nameLabel.Size = UDim2.fromScale(1, 1)
		nameLabel.TextWrapped = true
	end

	if slot.count > 1 then
		local countLabel = makeLabel(cell, `x{slot.count}`, 14)
		countLabel.AnchorPoint = Vector2.new(1, 1)
		countLabel.Position = UDim2.new(1, -6, 1, -4)
		countLabel.Size = UDim2.fromOffset(40, 16)
		countLabel.TextXAlignment = Enum.TextXAlignment.Right
	end

	if itemId == equippedId then
		local outline = Instance.new("UIStroke")
		outline.ApplyStrokeMode = Enum.ApplyStrokeMode.Border
		outline.Color = COLOURS.equipped
		outline.Thickness = 3
		outline.Parent = cell
	end

	cell.MouseEnter:Connect(function()
		info.Text = if item then `{item.name}: {item.description}` else name
	end)
	cell.Activated:Connect(function()
		-- 是请求,而不是命令:服务端检查请求并发回结果
		if item and item.toolName then
			equipItem:FireServer(itemId)
		elseif item and item.heal then
			useItem:FireServer(itemId)
		end
	end)
end

local function render(snapshot: Snapshot)
	for _, child in grid:GetChildren() do
		if child:IsA("GuiButton") then
			child:Destroy()
		end
	end
	for index = 1, snapshot.capacity do
		makeCell(index, snapshot.slots[index], snapshot.equipped)
	end
	slotCount.Text = `{#snapshot.slots} / {snapshot.capacity} slots`
end

-- 服务端在加载后和每次修改后发送这个
inventoryUpdated.OnClientEvent:Connect(render)

-- 3. 用按钮或 B 键打开和关闭
local function toggle()
	panel.Visible = not panel.Visible
end

openButton.Activated:Connect(toggle)
UserInputService.InputBegan:Connect(function(input: InputObject, gameProcessedEvent: boolean)
	if not gameProcessedEvent and input.KeyCode == TOGGLE_KEY then
		toggle()
	end
end)

StarterPlayerScripts 中的 LocalScript 每次会话只运行一次,而 ResetOnSpawn = false 让 ScreenGui 在角色重生时保留,所以网格会继续显示服务端发来的最后一份副本。

客户端为每个格子绘制一个单元格,包括空格子,所以 20 格的背包看起来始终是 20 格。每次更新都会销毁旧的单元格并创建新的,这种方法简单,适合几十个格子。如果服务端在这个脚本连接之前就发送了 InventoryUpdated,Roblox 会把消息放进队列,并在处理函数连接后立即送达,所以第一份背包不会丢失。

想在 Studio 里画好窗口?做一个带一个模板格子的 ScreenGui,在 makeCell 中对它 Clone。要显示图标,就在目录中给物品设置 icon,填入你上传的图片,它的单元格就会显示图片而不是名称。

测试背包

  1. 点击 Play。用左侧的按钮或 B 键打开背包:新玩家拥有 Sword 和 3 个 Apple,计数显示 2 / 20 slots。在 Studio 无法访问数据存储时,物品会在几秒后出现(Output 中会先出现加载警告),而且不会被保存。
  2. 点击 Sword。剑会出现在你手中和快捷栏里,它的格子会出现紫色边框。再点一次收起它。
  3. 走到零件 Apple 旁边,使用它的提示。苹果堆叠会增加到 4 个,零件会消失 15 秒。
  4. 要测试治疗,先降低生命值。把 Client/Server 切换到 Server,在 Explorer 中选中你角色的 Humanoid,把 Health 设为 50,切换回 Client,然后点击 Apple。
  5. 在开启 Studio 对 API services 的访问后,停止游戏并重新运行。捡到的苹果还在。如果加载或保存失败,Output 会告诉你。

要用多名玩家测试,在测试设置中选择 Server & Clients,设置 2 个客户端。每个玩家只能看到自己的背包,而另一个人手里的剑两人都能看到。

常见错误与解决办法

大多数问题会在 Output 窗口中显示为警告或红色错误行。请先看第一条:后面的错误往往是由它引起的。

WaitForChild 调用处出现 Infinite yield possible

脚本在等待一个不存在、名字也不完全一致的对象。把你的 Explorer 和第 1 步中的层级树对比一下:ReplicatedStorage 中带三个 RemoteEvent 的 InventoryRemotes、ServerStorage 中的 ItemTools,以及两个模块。名字区分大小写。脚本错误教程 对这个警告有更详细的说明。

网格能打开,但一直是空的

客户端只绘制服务端发来的内容。在 Output 中查找 Inventory load failed 警告,并确认 InventoryData 是 ServerScriptService 中的 Script 而不是 LocalScript,旁边还有 ModuleScript InventoryService。如果 Output 显示 Remote event invocation 错误,说明客户端上没有人在监听 InventoryUpdated:请查找来自 InventoryClient 的更早的错误。

每次在 Studio 里玩,物品都会重置

如果 Output 显示 Inventory not loaded: playing with starter items that will not be saved,说明场景还没有发布,或者 Studio 对 API services 的访问已关闭。按第 4 步中的说明,在你游戏的测试副本中开启它。

点击剑没有任何反应

在 Output 中查找 Cannot equip sword:ServerStorage.ItemTools 中的 Tool 名字必须与目录中的 toolName 完全一致。另外,Tool 需要一个名为 Handle 的零件才能被拿在手里,除非你把它的 RequiresHandle 设为 false。

拾取提示出现了,但什么都没有添加

ItemId Attribute 必须与目录中的 id 完全一致,包括大小写:是 apple,而不是 Apple。玩家的背包还在加载时,或者放不下全部数量时,都不会添加任何东西。

我改了保存的内容之后,保存就失败了

数据存储只接受简单数据:字符串、数字、布尔值以及由它们组成的表。保存 Tool、Part 或任何其他 Instance 会失败,或者值被保存为 nil。请保存物品 id 和数量,其他一切都从目录中恢复,就像 serialize 那样。

用 RoCode 来做

如果你觉得描述系统比手工搭建更容易,RoCode 可以在你打开的场景里把它搭好。它是 Roblox Studio 的 AI 代理:你在网页聊天里描述功能,它的 Studio 插件就会在你的 Explorer 中创建脚本和对象,而不是给你一段要粘贴的代码。

你输入

添加一个 20 格、物品可堆叠的背包,一个按 B 打开的网格界面,一把玩家可以装备的 ServerStorage 中的剑,能治疗的苹果,以及通过 DataStoreService 保存。

RoCode 的操作
  • 在某一步需要时,可以用 Search Game 和 Search Scripts 查看你的场景,以便基于已有的物品、Remote 或存档代码来构建,而不是再加一套系统
  • 用 Create Instance 创建文件夹和 RemoteEvent,用 Create Script 创建 ModuleScript、Script 和 LocalScript
  • 可以用 Build UI 搭出窗口的雏形,其中有带占位格子的背包布局;从服务端填充格子的代码由单独的脚本编写
  • 用 Check Script 在 Studio 中检查每个脚本能否编译,它能发现编译错误和几种有风险的写法,但不做类型检查,不做 lint,也不运行你的代码

每批改动都是 Studio 中的一个撤销点。RoCode 无法开启 Studio 对 API services 的访问,这需要你自己来做。使用插件 3.9 及以上时,它可以运行简短的试玩测试并读取错误;使用插件 3.9.15 及以上时,它的测试角色可以按键和装备物品,但它只检查自己决定要测试的内容,所以请自己通过试玩测试检查保存功能。背包建立在存档和工具等其他系统之上,而 在你自己的 Studio 场景里构建的 AI 游戏制作工具 会每次用一个提示词把它们逐个加上。RoCode 如何连接到 Studio。

常见问题

应该用 Roblox 的 Backpack 代替自己的背包吗?

Backpack 是 Roblox 内置的背包:里面的每个 Tool 都会在快捷栏中显示为一个按钮。如果你游戏里的所有物品都是 Tool,并且不需要堆叠、数量和格子上限,它可能就够用了,不过你仍然得自己保存每个玩家拥有哪些 Tool。对于不是 Tool 的物品,比如材料和消耗品,就需要自己的背包。本教程两者都用:背包保存一切,Backpack 放已装备的 Tool。

如何隐藏 Roblox 默认的快捷栏?

在 LocalScript 中调用 StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.Backpack, false)。快捷栏隐藏后,玩家需要另一种方式来拿起和收起已装备的 Tool,例如一个请求服务端调用 Humanoid:EquipTool 或 Humanoid:UnequipTools 的按钮。

如何让格子保持固定位置以支持拖放?

保存一个固定长度、每个格子一项的列表,用空 id 这样的值而不是 nil 来标记空格子,因为 Roblox 不建议通过 RemoteEvent 发送带 nil 的表。然后添加一个发送两个格子编号的 RemoteEvent MoveItem,并让服务端在交换之前检查两者都是 1 到容量之间的整数。

保存的背包最大能有多大?

数据存储中的一个值在序列化后最多可以占用 4,194,304 个字符(依据 2026 年 9 月 30 日的文档)。id 和数量的列表只占其中极小的一部分。让存档变大的是每个物品附带的文本,比如为每个物品保存的自定义名称或长说明。

如何用金币买卖物品?

全部在服务端完成。出售时调用 InventoryService.remove,只有它返回 true 时才付款。购买时检查价格和 spaceFor,扣除金币,然后调用 add。商店教程 搭建了购买这一侧。

参考资料

代码如何验证:本页的所有脚本都已用 Roblox API 类型定义(luau-lsp,2026年11月20日)通过 Luau strict 类型检查。类型检查能发现 API 名称写错和类型不匹配,但发现不了游戏逻辑上的错误。发布前请务必在 Studio 中测试。

在你自己的游戏里试试 RoCode。

每天有免费额度,无需绑定银行卡。安装插件,描述你想要的功能,然后看看它在 Studio 里做了什么。