Сохранение при выходе
Урок 19 из 20 курса Игра в Roblox: симулятор питомцев на Coddy.
Монеты, пустыня и все питомцы должны оставаться на месте, когда игрок присоединится в следующий раз. DataStore хранит таблицу для каждого игрока под его UserId. Питомцы — это экземпляры, которые DataStore хранить не может, поэтому сохраняйте обычную таблицу с именем каждого питомца и указанием, экипирован ли он:
{ Coins = 340, Desert = false, Pets = { { Name = "Bunny", Equipped = true } } }Сохраняйте данные, когда игрок выходит (PlayerRemoving), а также, если сервер завершает работу, пока в нём ещё есть игроки, в game:BindToClose. Сохранение может завершиться с ошибкой на стороне Roblox, поэтому оберните его в pcall:
pcall(function()
saveStore:SetAsync(player.UserId, data)
end)В Roblox Studio DataStore работают после публикации игры, если включён параметр Enable Studio Access to API Services.
Задание
СложноСохраняйте игру каждого игрока, когда он выходит.
- Получите
DataStoreServiceиlocal saveStore = DataStoreService:GetDataStore("Pets"). - Напишите
save(player): внутри pcall вызовитеsaveStore:SetAsync(player.UserId, data), передавCoins,DesertиPets— список{ Name = pet.Value, Equipped = ... }. - Вызовите эту функцию при
Players.PlayerRemovingи для каждого игрока вgame:BindToClose.
Нажмите «Играть», заработайте монеты и нажмите «Стоп»: данные сохранятся при выходе. Затем нажмите «Проверить».
Попробуйте сами
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local RunService = game:GetService("RunService")
local Settings = require(game.ReplicatedStorage.Settings)
local remotes = game.ReplicatedStorage.Remotes
local piles = workspace.Piles
local petParts = workspace.PetParts
local pileSpot = {} -- каждая куча -> место, на котором она стоит
local lastHit = {} -- каждый игрок -> время его последнего удара
print("A Meadow pile gives " .. Settings.PileValue .. " coins")
-- Settings.Pets по имени
local petInfo = {}
for _, info in Settings.Pets do
petInfo[info.Name] = info
end
-- Питомец: StringValue в папке Pets игрока, где хранится его имя, а
-- редкость и сила хранятся в атрибутах
local function givePet(player, name, equipped)
local info = petInfo[name]
local pet = Instance.new("StringValue")
pet.Name = "Pet"
pet.Value = name
pet:SetAttribute("Rarity", info.Rarity)
pet:SetAttribute("Power", info.Power)
pet:SetAttribute("Equipped", equipped)
pet.Parent = player.Pets
return pet
end
-- сколько питомцев выпущено у игрока
local function equippedCount(player)
local count = 0
for _, pet in player.Pets:GetChildren() do
if pet:GetAttribute("Equipped") then
count += 1
end
end
return count
end
-- сколько силы питомцы игрока добавляют к каждому удару
local function petPower(player)
local power = 0
for _, pet in player.Pets:GetChildren() do
if pet:GetAttribute("Equipped") then
power += pet:GetAttribute("Power")
end
end
return power
end
-- Каждый игрок получает Coins в таблице лидеров
Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local coins = Instance.new("IntValue")
coins.Name = "Coins"
coins.Parent = leaderstats
-- принадлежащие игроку питомцы
local pets = Instance.new("Folder")
pets.Name = "Pets"
pets.Parent = player
end)
-- Куча монет на месте появления: копия ServerStorage.CoinPile, у которой здоровье
-- и ценность хранятся в атрибутах
local function spawnPile(spot)
local desert = spot.Parent.Parent.Name == "Desert"
local health = desert and Settings.DesertHealth or Settings.PileHealth
local pile = ServerStorage.CoinPile:Clone()
pile.Position = spot.Position
pile:SetAttribute("MaxHealth", health)
pile:SetAttribute("Health", health)
pile:SetAttribute("Value", desert and Settings.DesertValue or Settings.PileValue)
pile:SetAttribute("Zone", spot.Parent.Parent.Name)
pile.HealthGui.Label.Text = pile:GetAttribute("Health") .. "/" .. pile:GetAttribute("MaxHealth")
pileSpot[pile] = spot
pile.Parent = piles
return pile
end
-- Удар уменьшает здоровье кучи на 1 плюс суммарную силу питомцев игрока;
-- при 0 куча разрушается, а игрок получает монеты по её стоимости
local function hitPile(player, pile)
local health = pile:GetAttribute("Health") - (1 + petPower(player))
if health > 0 then
pile:SetAttribute("Health", health)
pile.HealthGui.Label.Text = health .. "/" .. pile:GetAttribute("MaxHealth")
return
end
player.leaderstats.Coins.Value += pile:GetAttribute("Value")
local spot = pileSpot[pile]
pileSpot[pile] = nil
pile:Destroy()
-- через несколько секунд на том же месте появляется новая куча
task.delay(Settings.RespawnTime, spawnPile, spot)
end
-- На каждом месте в каждой зоне — по куче
for _, zone in workspace.Zones:GetChildren() do
for _, spot in zone.Spawns:GetChildren() do
spawnPile(spot)
end
end
-- Клиент запрашивает удар по куче. Никогда не доверяйте клиенту: кто угодно может вызвать
-- это удалённое событие с любыми данными, откуда угодно и с какой угодно частотой.
remotes.Hit.OnServerEvent:Connect(function(player, pile)
-- настоящая куча
if typeof(pile) ~= "Instance" or pile.Parent ~= piles then
return
end
-- в пределах досягаемости
local character = player.Character
local root = character and character:FindFirstChild("HumanoidRootPart")
if not root or (root.Position - pile.Position).Magnitude > Settings.Reach then
return
end
-- не слишком часто
local now = time()
if lastHit[player] and now - lastHit[player] < Settings.HitCooldown then
return
end
lastHit[player] = now
-- в зоне, которую игрок открыл
if pile:GetAttribute("Zone") == "Desert" and not player:GetAttribute("Desert") then
return
end
hitPile(player, pile)
end)
-- Взвешенный выбор: Chance каждого питомца (из 100) — его доля на шкале
local function rollPet()
local roll = math.random() * 100
for _, info in Settings.Pets do
roll -= info.Chance
if roll <= 0 then
return info.Name
end
end
return Settings.Pets[1].Name
end
-- Вылупление: запрос у яйца, оплачиваемый монетами
workspace.Egg.ProximityPrompt.Triggered:Connect(function(player)
local coins = player.leaderstats.Coins
if coins.Value < Settings.EggPrice then
return
end
coins.Value -= Settings.EggPrice
local name = rollPet()
-- сразу выпустить, если есть место
local pet = givePet(player, name, equippedCount(player) < Settings.MaxEquipped)
print(player.Name .. " hatched a " .. name)
-- Все узнают о самых редких питомцах
if pet:GetAttribute("Rarity") == "Legendary" then
remotes.Announce:FireAllClients(player.Name, name)
end
end)
-- Выпущенные питомцы следуют за хозяином: у каждого есть своя деталь в игровом мире, которая
-- каждый кадр располагается в ряду позади игрока
local petModels = {} -- каждый питомец -> его деталь в игровом мире
RunService.Heartbeat:Connect(function()
for _, player in Players:GetPlayers() do
local root = player.Character and player.Character:FindFirstChild("HumanoidRootPart")
local pets = player:FindFirstChild("Pets")
local slot = 0
for _, pet in pets and pets:GetChildren() or {} do
local model = petModels[pet]
if pet:GetAttribute("Equipped") and root then
slot += 1
if not model then
model = ServerStorage.PetModels[pet.Value]:Clone()
model.Parent = petParts
petModels[pet] = model
end
model.CFrame = root.CFrame * CFrame.new((slot - 2) * 3, -1.5, 4)
elseif model then
-- питомец убран: его деталь удаляется
model:Destroy()
petModels[pet] = nil
end
end
end
end)
-- Клиент запрашивает выпуск или уборку питомца. Сервер проверяет, что питомец
-- принадлежит игроку и выпущено не больше MaxEquipped питомцев.
remotes.Equip.OnServerEvent:Connect(function(player, pet)
if typeof(pet) ~= "Instance" or pet.Parent ~= player.Pets then
return
end
if pet:GetAttribute("Equipped") then
pet:SetAttribute("Equipped", false)
elseif equippedCount(player) < Settings.MaxEquipped then
pet:SetAttribute("Equipped", true)
end
end)
-- Ворота Desert: заплатите один раз, и они откроются только для этого игрока
workspace.Gate.ProximityPrompt.Triggered:Connect(function(player)
local coins = player.leaderstats.Coins
if player:GetAttribute("Desert") or coins.Value < Settings.GatePrice then
return
end
coins.Value -= Settings.GatePrice
player:SetAttribute("Desert", true)
end)
-- Урок 19: здесь будет сохранение при выходе
Все уроки раздела Игра в Roblox: симулятор питомцев
Потренируйтесь самостоятельно: Песочница Roblox