# DataStoreService（ロブロックス クラス）

> プレイヤーのコインやレベルなどのデータを、ゲームを終了しても残るように保存するためのサービスです。

- URL：https://roblox.minecraft-okinawa.com/reference/classes/DataStoreService/
- 公式：https://create.roblox.com/docs/reference/engine/classes/DataStoreService
- 受け継いでいるクラス：Instance

データの保存と読み込みは、通信の失敗で止まることがあるため、pcallで包んで使うのが基本です。Roblox Studioで試すときは、ゲームの設定でAPIサービスへのアクセスを有効にする必要があります。

## 使用例：コインを保存・読み込みする

（Script／置く場所：ServerScriptService）

```lua
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)
```

## メソッド

- `DataStoreService:GetDataStore(name: string, scope: string, options: Instance): DataStore`：名前を指定して、データを保存する場所（データストア）を取り出します。
- `DataStoreService:GetGlobalDataStore(): DataStore`：Returns the default data store.
- `DataStoreService:GetOrderedDataStore(name: string, scope: string): OrderedDataStore`：Get an OrderedDataStore given a name and optional scope.
- `DataStoreService:GetRequestBudgetForRequestType(requestType: DataStoreRequestType): int`：Returns the number of requests that can be made by the given request type.
- `DataStoreService:ListDataStoresAsync(prefix: string, pageSize: int, cursor: string): DataStoreListingPages`：Returns a DataStoreListingPages object for enumerating through all of the experience's data stores.
- `DataStoreService:SetRateLimitForRequestType(requestType: DataStoreRequestType, baseLimit: int, perPlayerLimit: int): ()`：Sets the rate limit for a given request type per minute.

英語の説明とメンバー一覧：Roblox Creator Documentation（CC BY 4.0）。日本語の解説はこのサイト独自のものです。

執筆：鈴木孝昌（現役プロジェクトマネージャー／プログラミング講師）／運営：沖縄マイクラ部 プログラミングスクール「クロスウェーブ」（https://minecraft-okinawa.com/）