データを保存する(DataStoreService)
中級作例更新日:2026年11月13日Luauの型チェック済み
ひとことで言うと
プレイヤーのコインの数を、ゲームを終了しても残るように保存・読み込みします。
この記事で使うAPI
完成するもの
プレイヤーのコインの数を、ゲームを終了しても残るように保存・読み込みします。
スクリプト
(Script/置く場所:ServerScriptService)
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local coinStore = DataStoreService:GetDataStore("PlayerCoins")
Players.PlayerAdded:Connect(function(player)
local success, coins = pcall(function()
return coinStore:GetAsync(tostring(player.UserId))
end)
if success then
print(player.Name .. " のコイン:" .. tostring(coins or 0))
else
warn("データを読み込めませんでした")
end
end)
Players.PlayerRemoving:Connect(function(player)
local success, err = pcall(function()
coinStore:SetAsync(tostring(player.UserId), 100)
end)
if not success then
warn("データを保存できませんでした:" .. tostring(err))
end
end)
しくみ
参加したときにGetAsyncで読み込み、退出するときにSetAsyncで保存します。通信の失敗に備えて、どちらもpcallで包んでいます。
Roblox Studioで試すときは、ゲームの設定で「APIサービスへのStudioアクセスを有効にする」をオンにする必要があります。
アレンジしてみよう
- 保存する値を、leaderstatsのコインの数にする
- 定期的に保存して、急な切断に備える