튜토리얼 · 게임 시스템

Roblox Studio에서 인벤토리 만드는 법

인벤토리는 UI 작업처럼 보이지만, 해킹당할 수 있는지와 아이템을 잃어버리는지는 아이템을 어디에 보관하느냐로 결정됩니다. 이 가이드에서는 각 플레이어의 아이템을 서버의 테이블에 두고, 각 플레이어가 그 사본을 받아 그리드로 그리며, 서버가 검증하는 요청으로 Tool을 장착하고 소모품을 쓰고, 모든 것을 데이터 스토어에 저장합니다.

업데이트: 2026년 11월 20일읽는 데 11분작성:

요약

각 플레이어의 아이템은 서버의 테이블, 즉 ServerScriptService의 ModuleScript 안에 보관하고, 아이템을 추가하고 빼고 스택으로 쌓는 일은 이 코드만 하게 하세요. 아이템은 ReplicatedStorage의 ModuleScript에 한 번만 정의합니다(id, 이름, 최대 스택). 변경이 있을 때마다 서버가 그 플레이어에게 RemoteEvent로 인벤토리 사본을 보내고, LocalScript가 ScrollingFrame과 UIGridLayout으로 그리드를 그립니다.

  • 클라이언트는 절대 아이템을 추가하지 않습니다. "내 칼을 장착해 줘"처럼 요청만 할 수 있고, 서버는 무언가를 하기 전에 플레이어가 그 아이템을 가지고 있는지 확인합니다.
  • 아이템은 내가 제어하는 서버 코드로만 생깁니다: 줍기, 서버에서 확인한 상점 구매, 보상.
  • Tool이 아니라 아이템 id와 개수를 DataStoreService로 저장하세요. 플레이어가 나갈 때, 서버가 꺼질 때, 그리고 몇 분마다 저장합니다. 데이터를 불러오지 못한 플레이어는 절대 저장하지 마세요.
이 페이지의 내용
  1. 구조
  2. 아이템이 서버에 있는 이유
  3. 1. Explorer 준비
  4. 2. 아이템 카탈로그
  5. 3. 서버의 인벤토리
  6. 4. 불러오기와 저장
  7. 5. 아이템 줍기
  8. 6. 장착과 사용
  9. 7. 그리드 UI
  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) 같은 리모트로 고치면, 치터가 그 이벤트를 아무 인수로 원하는 만큼 직접 호출할 수 있습니다. Roblox 보안 가이드는 클라이언트가 보낸 것은 모두 쓰기 전에 서버가 검증해야 한다고 말합니다.

그래서 이 가이드에서 클라이언트는 플레이어가 이미 가진 아이템으로 무언가를 해 달라고 요청만 할 수 있습니다. "이걸 장착해 줘"와 "이걸 사용해 줘"입니다. 각 요청에는 아이템 id 하나만 있고 개수는 없으며, 서버에서 한 번의 검사를 거칩니다. 문자열인지, 그런 아이템이 존재하는지, 플레이어가 적어도 하나는 가지고 있는지, 1초에 네 번보다 많이 요청하지 않는지입니다. 그다음 서버가 카탈로그로 Tool을 직접 찾습니다. 같은 가이드가 경고하듯, 서버는 클라이언트로부터 Tool, 경로, 인스턴스를 절대 받지 않습니다.

아이템은 서버 코드를 통해서만 인벤토리에 들어갑니다. 서버가 확인한 줍기, 서버가 돈을 차감한 구매(상점 가이드에서 만듭니다), 퀘스트 보상이나 드롭입니다. 다른 종류의 인수를 검증하는 방법을 포함해 리모트 전반에 대해서는 RemoteEvent 가이드를 읽어 보세요.

1단계: Explorer 준비하기

다음 오브젝트를 직접 만드세요. 다음 단계의 스크립트들은 이름으로 찾으므로, 이름을 모두 여기 적힌 그대로 쓰세요.

  1. ReplicatedStorage에 이름이 InventoryRemotes인 Folder를 넣으세요. 그 안에 이름이 InventoryUpdated, EquipItem, UseItem인 RemoteEvent 세 개를 넣으세요.
  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

require 뒤의 type 줄과 :: 캐스트는 WaitForChild로 찾은 모듈이 무엇을 돌려주는지 모르는 Luau 타입 검사기를 위한 것일 뿐입니다. 게임 실행 중에는 아무것도 바꾸지 않습니다. 이 가이드의 다른 스크립트도 같은 방식을 씁니다.

사과가 10개까지 쌓이는 위 카탈로그에서 스택 규칙이 작동하는 방식:

  • 사과 7개짜리 스택이 있는 플레이어에게 사과 15개를 추가하면, 그 스택이 10개로 채워진 다음 5개짜리 새 스택이 시작됩니다.
  • 슬롯이 모자라면 add는 들어가는 만큼만 추가하고 그 개수를 돌려줍니다. 전부 아니면 전무가 필요할 때는 5단계의 줍기처럼 먼저 spaceFor를 호출하세요.
  • remove는 전부 아니면 전무 방식입니다. 사과가 2개인 플레이어에게서 3개를 빼려고 하면 아무것도 빼지 않고 false를 돌려주므로, 무언가를 대신 주기 전에 결과를 확인하세요.
  • 슬롯에는 빈 구멍이 없습니다. 슬롯이 비면 나머지가 위로 당겨집니다. 이렇게 하면 목록을 보내고 저장하기가 더 쉽습니다. 위치를 유지하는 슬롯은 마지막 FAQ에서 다룹니다.
다른 서버 스크립트가 호출할 수 있는 것
함수돌려주는 값용도
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단계: 모든 인벤토리를 불러오고 저장하기

인벤토리는 서버 메모리에 있으므로 플레이어가 나가면 사라집니다. 이 스크립트는 플레이어가 들어올 때 데이터 스토어에서 슬롯을 불러오고, 나갈 때, 서버가 꺼질 때, 그리고 서버가 크래시할 경우에 대비해 3분마다 다시 기록합니다. 아이템 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초를 줍니다.
  • 한도 넘지 않기. 플레이어당 3분마다 한 번, 그리고 나갈 때 한 번 기록하는 것은 서버 기본 예산인 분당 60회 + 플레이어당 40회(2026년 9월 30일 기준 문서)보다 훨씬 적습니다. User_ 키 패턴은 Roblox 권장 사항에서 가져왔고, SetAsync에 user ID를 넘기면 데이터가 그 플레이어와 연결되는데, Roblox는 데이터 삭제 요청 처리를 위해 이것을 강력히 권장합니다.

작은 게임이라면 이것이 탄탄한 기반입니다. 서버를 빠르게 옮긴 플레이어가 이전 서버가 저장하기 전에 데이터를 불러오지 못하게 막는 세션 잠금, 그리고 SetAsync 대신 UpdateAsync를 써야 할 때는 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에 속성 두 개를 주세요:
-- 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일 때도 프롬프트 이벤트를 일으킬 수 있고, 고정되지 않은 파트를 자기 캐릭터 쪽으로 끌어올 수 있습니다. 그래서 스크립트가 Enabled와 거리를 직접 확인하고, 파트는 고정되어 있습니다.

다른 서버 스크립트도 같은 방식으로 아이템을 줍니다. 구매, 퀘스트, 처치 뒤에 위 스크립트들처럼 require로 InventoryService를 불러와 InventoryService.add(player, "wood", 5)를 호출하세요. 아이템을 잃으면 안 될 때는 먼저 spaceFor를 확인하세요. NPC도 아이템의 출처가 될 수 있습니다. NPC 대화 가이드에서는 대답이 서버에서 동작을 실행하며, 그 동작도 같은 방식으로 InventoryService.add를 호출할 수 있습니다.

6단계: Tool 장착과 아이템 사용

클라이언트가 할 수 있는 요청은 RemoteEvent 두 개가 전달하는 것뿐입니다. EquipItem은 ServerStorage에서 아이템의 Tool 사본을 플레이어의 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문자열인지, 아이템이 존재하는지, 플레이어가 가졌는지, 요청이 1초에 네 번보다 많지 않은지, 아이템에 toolName이 있는지, 그 이름의 Tool이 ServerStorage.ItemTools에 있는지
UseItem아이템 id같은 타입, 소유, 빈도 확인, 아이템에 heal 값이 있는지, 캐릭터가 살아 있고 다쳤는지, 체력을 더하기 전에 아이템 하나를 뺐는지

Tool이 복제되거나 사라지지 않게 하는 세 가지 장치가 있습니다. 사본의 CanBeDropped는 false입니다. 떨어뜨린 Tool은 Workspace로 떨어져 다른 플레이어가 가져갈 수 있는데, 원본은 인벤토리에 그대로 남기 때문입니다. 모든 사본에는 InventoryItem 속성이 있어서, 장착을 해제할 때 어디에 있든 모든 사본을 찾아 없앨 수 있습니다. 그리고 플레이어에게 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와 Apple 3개가 있고 카운터는 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 경고를 찾아보고, ServerScriptService의 InventoryData가 LocalScript가 아닌 Script인지, 옆에 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로 저장됩니다. serialize처럼 아이템 id와 개수를 저장하고, 나머지는 카탈로그에서 복원하세요.

RoCode로 만들기

직접 만드는 것보다 시스템을 설명하는 편이 쉽다면, RoCode가 지금 열려 있는 플레이스에 만들어 줄 수 있습니다. Roblox Studio용 AI 에이전트입니다. 웹 채팅에서 기능을 설명하면 Studio 플러그인이 붙여 넣을 코드를 건네주는 대신 Explorer에 스크립트와 오브젝트를 만듭니다.

입력하는 내용

아이템 스택이 되는 20슬롯 인벤토리, B로 열리는 그리드 UI, 플레이어가 장착할 수 있는 ServerStorage의 칼, 회복하는 사과, 그리고 DataStoreService로 저장하는 기능을 추가해 줘.

RoCode가 하는 일
  • 단계에 필요할 때 Search Game과 Search Scripts로 플레이스를 살펴서, 시스템을 하나 더 추가하는 대신 이미 있는 아이템, 리모트, 저장 코드를 바탕으로 만들 수 있습니다
  • Create Instance로 폴더와 RemoteEvent를, Create Script로 ModuleScript, Script, LocalScript를 만듭니다
  • Build UI로 창의 뼈대를 만들 수 있으며, 여기에는 임시 슬롯이 있는 인벤토리 레이아웃이 있습니다. 서버에서 슬롯을 채우는 코드는 별도 스크립트로 작성됩니다
  • Check Script로 Studio에서 각 스크립트의 컴파일을 확인합니다. 이 도구는 컴파일 오류와 몇 가지 위험한 패턴을 잡아내지만, 타입 검사나 린트를 하지 않고 코드를 실행하지도 않습니다

변경 묶음마다 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 호출을 요청하는 버튼입니다.

드래그 앤 드롭을 위해 슬롯이 위치를 유지하게 하려면 어떻게 하나요?

슬롯마다 항목이 하나인 고정 길이 목록을 보관하고, 빈 슬롯은 nil 대신 빈 id 같은 값으로 표시하세요. Roblox는 nil이 든 테이블을 RemoteEvent로 보내지 말라고 권하기 때문입니다. 그다음 슬롯 번호 두 개를 보내는 RemoteEvent MoveItem을 추가하고, 서버가 둘 다 1부터 용량 사이의 정수인지 확인한 뒤 맞바꾸게 하세요.

저장된 인벤토리는 얼마나 클 수 있나요?

데이터 스토어의 값 하나는 직렬화 후 최대 4,194,304자까지 될 수 있습니다(2026년 9월 30일 기준 문서). id와 개수 목록은 그중 아주 작은 부분만 차지합니다. 저장 크기를 키우는 것은 아이템마다 붙는 텍스트, 예를 들어 아이템마다 저장한 사용자 지정 이름이나 긴 설명입니다.

코인으로 아이템을 사고팔려면 어떻게 하나요?

모두 서버에서 하세요. 팔 때는 InventoryService.remove를 호출하고 true를 돌려줬을 때만 돈을 주세요. 살 때는 가격과 spaceFor를 확인하고, 코인을 차감한 뒤 add를 호출하세요. 상점 가이드에서 구매 쪽을 만듭니다.

출처와 더 읽을거리

코드 검증 방법: 이 페이지의 모든 스크립트는 Roblox API 정의를 적용한 Luau의 엄격한 타입 검사기(luau-lsp, 2026년 11월 20일)를 통과합니다. 타입 검사는 잘못 쓴 API 이름과 잘못된 타입을 찾아내지만 게임 로직의 오류는 찾지 못하므로, 게시하기 전에 Studio에서 직접 테스트하세요.

내 게임에서 RoCode를 사용해 보세요.

매일 무료 크레딧, 카드 등록 없이 시작합니다. 플러그인을 설치하고, 원하는 기능을 설명한 뒤, Studio에 만들어진 결과를 확인하세요.