重點摘要
把每位玩家的物品放在伺服器上的表格中,也就是 ServerScriptService 中的 ModuleScript,而且只有這段程式碼能新增、移除物品並把它們堆疊起來。在 ReplicatedStorage 中的 ModuleScript 裡把物品定義一次(id、名稱、最大堆疊數)。每次變更之後,伺服器會用 RemoteEvent 把該玩家的背包副本傳給他,再由 LocalScript 透過 ScrollingFrame 與 UIGridLayout 把它畫成格狀。
- 用戶端絕對不會新增物品。它只能提出請求,例如「裝備我的劍」,伺服器會先確認玩家真的有這把劍,才做任何事。
- 物品只會透過你掌控的伺服器程式碼出現:撿取、經伺服器檢查後的商店購買,以及獎勵。
- 用 DataStoreService 儲存物品 id 與數量,而不是 Tool,時機是玩家離開時、伺服器關閉時,以及每隔幾分鐘一次。絕對不要儲存資料沒有成功載入的玩家。
本頁內容
背包系統是怎麼組成的
這個系統由六個小部分組成,每個部分只負責一件事。所有和物品有關的規則都放在同一個伺服器模組裡,所以出問題時,只需要找一個地方。
| 部分 | 類型與位置 | 作用 |
|---|---|---|
ItemCatalog | ReplicatedStorage 中的 ModuleScript | 定義每個物品是什麼:名稱、說明、最大堆疊數,以及能不能裝備或使用。伺服器與所有用戶端都會讀取它。 |
InventoryService | ServerScriptService 中的 ModuleScript | 保存所有玩家的欄位。唯一能新增、移除物品並把它們堆疊起來的程式碼。 |
InventoryData | ServerScriptService 中的 Script | 在玩家加入時載入他的物品,並負責儲存。 |
InventoryActions | ServerScriptService 中的 Script | 檢查並執行裝備與使用的請求。 |
ItemPickup | Part 裡的 Script | 把物品交給撿起它的人。 |
InventoryClient | StarterPlayerScripts 中的 LocalScript | 畫出格子並傳送請求。它自己不會改變任何東西。 |
資料只往一個方向流動。伺服器變更背包後,把整個背包用 InventoryUpdated 傳給該玩家,用戶端再重新畫出來。玩家點擊欄位時,用戶端會傳送帶有物品 id 的 EquipItem 或 UseItem;伺服器檢查請求、做出變更,新的副本再循同一條路傳回來。傳送整個背包比只傳送變更簡單,而且只有幾十個欄位時,訊息仍然很小。
為什麼用戶端絕對不能新增物品
你可能會想直接在顯示物品的 LocalScript 中新增物品:玩家一點,欄位就填滿了。這會以兩種方式出問題。
- 其他人都看不到。LocalScript 中的變更只存在於該玩家的裝置上。伺服器不會知道,所以它不會被儲存,也沒有任何伺服器 Script 能使用它。
- 任何人都能偽造。如果你用
AddItem(itemId, amount)這樣的 remote 來修正,作弊者就能自己呼叫這個事件,帶任何參數、呼叫任意次數。Roblox 的安全指南說,伺服器在使用用戶端傳來的任何東西之前,都必須先檢查。
所以在這篇教學中,用戶端只能對玩家已經擁有的物品提出請求:「裝備這個」與「使用這個」。每個請求只帶一個物品 id,不帶任何數量,並在伺服器上通過同一道檢查:它是字串、這個物品存在、玩家至少有一個,而且玩家每秒送出的請求不超過四個。接著伺服器自己從目錄中找出 Tool。它絕對不接受用戶端傳來的 Tool、路徑或 instance,同一份指南也提醒過這一點。
物品只會透過伺服器程式碼進入背包:經伺服器檢查的撿取、由伺服器扣款的購買(商店教學會做出這部分)、任務獎勵或掉落物。關於 remote 的整體觀念,以及其他類型參數的檢查方式,請看 RemoteEvent 教學。
步驟 1:準備 Explorer
手動建立這些物件。後面步驟的 Script 會依名稱尋找它們,所以每個名稱都要和這裡寫的一模一樣。
- 在 ReplicatedStorage 中插入一個名為
InventoryRemotes的 Folder。在裡面插入三個 RemoteEvent,分別命名為InventoryUpdated、EquipItem與UseItem。 - 在 ServerStorage 中插入一個名為
ItemTools的 Folder。在裡面插入一個名為Sword的 Tool,再在 Tool 裡插入一個名為Handle的 Part(1 x 4 x 1 stud 就很合適)。確認 Handle 的 Anchored 沒有勾選:Roblox 提醒,角色拿著含有錨定零件的工具時會卡在原地。你已經有的 Tool 也可以用,只要它的名稱和步驟 2 的目錄一致。 - 跟著步驟進行時再逐一加入 Script。下面的樹狀圖顯示每個 Script 要放在哪裡。
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,並把內容換成這段:
-- 遊戲中可能存在的所有物品。伺服器與所有用戶端都會讀取這份清單;
-- 只有伺服器能決定誰擁有什麼。
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 格的容量。其他伺服器 Script 會呼叫它的函式,除此之外沒有任何人會編輯這個表格。
在 ServerScriptService 中插入一個 ModuleScript,命名為 InventoryService:
-- 唯一會變更背包的程式碼。它放在 ServerScriptService,
-- 用戶端既看不到它,也無法執行它。
local ReplicatedStorage = game:GetService("ReplicatedStorage")
-- Strict 模式看不出透過 WaitForChild 取得的 require 回傳什麼,所以
-- 我們描述這個 Script 會用到的那部分模組
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
require 之後的 type 這幾行與 :: 型別轉換,只是給 Luau 型別檢查器看的,因為它看不出透過 WaitForChild 找到的模組回傳什麼。遊戲執行時它們不會改變任何事。這篇教學中的其他 Script 也是同樣做法。
以上面的目錄為例(蘋果最多堆疊到 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:載入並儲存每個背包
背包存在伺服器的記憶體中,所以玩家離開時就會消失。這個 Script 會在玩家加入時從資料儲存區載入他的欄位,並在他離開時、伺服器關閉時,以及每三分鐘(以防伺服器當機)寫回去。它只儲存物品 id 與數量:資料儲存區無法保存 Instance,例如 Tool。
在 ServerScriptService 中插入一個 Script,命名為 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 工作階段只會收到警告,而不會讓這個 Script 停止。
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
這個 Script 做了什麼、為什麼這樣做:
- 用預設值載入。新玩家沒有已儲存的值,所以
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 的零件,玩家使用它時就會加入物品。Script 在伺服器上監聽它的 Triggered 事件,所以物品是在用戶端無法插手的地方加入的。
- 在 Workspace 中加入一個 Part,命名為
Apple並塗成紅色。開啟 Anchored 並關閉 CanCollide,這樣它隱形時就不會有人撞到它。提示會顯示零件的名稱。 - 選取零件後,把 Properties 視窗捲到 Attributes 區塊,按下 +。新增類型為 string 的
ItemId並按 Save,再把值設為apple。用同樣方式新增類型為 number、值為1的Amount。 - 在零件中插入一個 Script,命名為
ItemPickup,並貼上這段程式碼:
-- 把這個 Script 放進 Part 裡,並給 Part 兩個屬性:
-- 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)
複製這個零件就能擺放更多物品。改變屬性,就能給予木頭、另一把劍或一疊蘋果。
Roblox 會替 Triggered 檢查距離,但它的安全指南仍然要求在伺服器上檢查提示:作弊者即使在 Enabled 為 false 時也能觸發提示事件,還能把沒有錨定的零件拉到自己的角色旁邊。所以 Script 會自己檢查 Enabled 與距離,零件也因此是錨定的。
其他任何伺服器 Script 都用同樣的方式給予物品。在購買、任務或擊殺之後,像上面的 Script 一樣用 require 載入 InventoryService,再呼叫 InventoryService.add(player, "wood", 5)。物品不能遺失時,請先檢查 spaceFor。NPC 也可以是另一個來源:在 NPC 對話教學中,一個回答會在伺服器上觸發動作,而這個動作也可以同樣呼叫 InventoryService.add。
步驟 6:裝備 Tool 與使用物品
兩個 RemoteEvent 承載了用戶端唯一能提出的請求。EquipItem 會把物品在 ServerStorage 中的 Tool 複製一份,放進玩家的 Backpack(畫面底部的快捷列)並放到他手上,再次請求則會收起來。UseItem 會移除一個可使用的物品並套用它的效果,這裡是回復生命值。
在 ServerScriptService 中插入一個 Script,命名為 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
-- 不管副本在哪裡(快捷列、手上或 StarterGear),都銷毀這個物品的 Tool
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 屬性,所以收起時可以找到並銷毀每一份副本,無論它在哪裡。如果玩家有 StarterGear 容器,就會在裡面放第二份副本。Roblox 每次角色出現時都會把 StarterGear 複製到 Backpack,所以裝備的劍在重生後會回來。
一次只能裝備一個 Tool,而且裝備狀態不會儲存,所以玩家重新加入後會從空的快捷列開始。如果之後要加入販售或丟棄功能,請在物品的最後一份離開背包之前先把它卸下。
可以把這把佔位用的劍換成真正能戰鬥的劍:照著 劍的教學做出 Tool,保留 Sword 這個名稱,並用它取代 ItemTools 中的佔位劍。那篇教學的伺服器 Script 會檢查每一次攻擊,不管玩家是怎麼拿到這把劍的。
步驟 7:畫出背包格子
LocalScript 會在程式碼中組出整個視窗,所以不需要手動擺放任何東西。ScrollingFrame 放置欄位,裡面的 UIGridLayout 把它們排成一列一列,而 AutomaticCanvasSize 會隨著列數增加擴大可捲動的區域。
在 Explorer 中打開 StarterPlayer,在 StarterPlayerScripts 中插入一個 LocalScript,命名為 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 格。每次更新都會銷毀舊的格子並建立新的,這很簡單,也適合幾十個欄位。如果伺服器在這個 Script 連接之前就傳送了 InventoryUpdated,Roblox 會把訊息排入佇列,等處理函式一連接就送達,所以第一份背包不會遺失。
想在 Studio 中畫出視窗?做一個只有一個欄位範本的 ScreenGui,然後在 makeCell 中對它呼叫 Clone。要使用圖示,就在目錄中替物品設定 icon,填入你上傳的圖片,它的格子就會顯示圖片而不是名稱。
測試背包
- 按下 Play。用左邊的按鈕或 B 鍵打開背包:新玩家會有 Sword 與 3 個 Apple,計數器顯示 2 / 20 slots。在 Studio 能存取資料儲存區之前,物品會在 Output 出現載入警告後幾秒才出現,而且不會被儲存。
- 點擊 Sword。劍會出現在你手上與快捷列中,它的欄位會出現紫色外框。再點一次就會收起來。
- 走到 Apple 零件旁並使用它的提示。蘋果堆疊會增加到 4 個,零件會消失 15 秒。
- 要測試回復生命值,先降低生命值。把 Client/Server 切換到 Server,在 Explorer 中選取自己角色的
Humanoid,把 Health 設為 50,再切換回 Client 並點擊 Apple。 - 開啟 Studio 的 API services 存取權後,停止遊戲再重新開始。撿到的蘋果還在。如果載入或儲存失敗,Output 會告訴你。
要用多位玩家測試,在測試設定中選擇 Server & Clients 並設定 2 個用戶端。每位玩家只看得到自己的背包,但另一位玩家手中的劍兩人都看得到。
常見錯誤與解法
大部分問題都會在 Output 視窗中以警告或紅色錯誤行的形式出現。請先看第一則:後面的錯誤常常是由它引起的。
WaitForChild 呼叫出現 Infinite yield possible
Script 在等待一個名稱不完全相符的物件。把你的 Explorer 和步驟 1 的樹狀圖比較:ReplicatedStorage 中含有三個 RemoteEvent 的 InventoryRemotes、ServerStorage 中的 ItemTools,以及兩個模組。名稱區分大小寫。Script 錯誤教學會更詳細地說明這個警告。
格子打得開,但一直是空的
用戶端只會畫出伺服器傳來的內容。在 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 屬性必須和目錄中的 id 完全相同,包括大小寫:是 apple 而不是 Apple。玩家的背包還在載入時,或空間不足以放下全部數量時,都不會加入任何東西。
我改了儲存的內容之後,存檔就壞了
資料儲存區只接受簡單的資料:字串、數字、布林值,以及由它們組成的表格。儲存 Tool、Part 或其他任何 Instance 會失敗,或者值會被存成 nil。請儲存物品 id 與數量,其餘的都從目錄還原,就像 serialize 的做法。
用 RoCode 製作
如果你覺得描述系統比手動組裝更容易,RoCode 可以在你開啟的場景中把它做出來。它是 Roblox Studio 的 AI 代理:你在網頁聊天中描述功能,它的 Studio 外掛程式會在你的 Explorer 中建立 Script 與物件,而不是給你一段要自己貼上的程式碼。
加入一個 20 格、物品可以堆疊的背包,一個按 B 打開的格狀 UI,一把玩家可以裝備、放在 ServerStorage 中的劍,能回復生命值的蘋果,以及用 DataStoreService 存檔。
- 在步驟需要時,可以透過 Search Game 與 Search Scripts 查看你的場景,沿用已經有的物品、remote 或存檔程式碼,而不是再加一套系統
- 用 Create Instance 建立資料夾與 RemoteEvent,用 Create Script 建立 ModuleScript、Script 與 LocalScript
- 可以用 Build UI 做出視窗雛形,裡面有帶佔位欄位的背包版面;從伺服器填入欄位的程式碼則由另外的 Script 撰寫
- 用 Check Script 在 Studio 中檢查每個 Script 能否編譯,它會抓出編譯錯誤與幾種有風險的寫法,但不檢查型別、不做 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 Creator Docs: Remote events and callbacks(英文). FireClient、OnServerEvent、參數的限制,以及沒有接收者的訊息如何排入佇列
- Roblox Creator Docs: Securing the client-server boundary(英文). 檢查 remote 的輸入資料、ProximityPrompt 的檢查,以及資料儲存區中的資料竄改
- Roblox Creator Docs: Data stores(英文). GetAsync、SetAsync,以及開啟 Studio 的存取權
- Roblox Creator Docs: Best practices for data stores(英文). 每位玩家一個鍵、鍵的格式與定期儲存
- Roblox Creator Docs: Data store error codes and limits(英文). 每個伺服器的請求限制與單一值的大小限制
- Roblox Creator Docs: In-game tools(英文). Handle、錨定、Backpack 與 StarterGear
- Roblox Creator Docs: Grid and table layouts(英文). UIGridLayout 的格子大小、間距與排序方式
程式碼如何驗證:本頁每一段 Script 都通過 Luau 嚴格型別檢查,並使用 Roblox API 定義(luau-lsp,2026年11月20日)。型別檢查能找出拼錯的 API 與錯誤的型別,但無法檢查遊戲邏輯,所以發布前請先在 Studio 中測試。