加入时加载
Coddy Roblox 游戏:宠物模拟器 课程的第 20 课,共 20 课。
现在,在玩家加入时读取已保存的数据。GetAsync 会返回 SetAsync 按键保存的内容;如果玩家从未保存过,则返回 nil。读取也可能失败,因此要在 pcall 中调用它。pcall 会返回调用是否成功,以及返回的值:
local ok, saved = pcall(function()
return saveStore:GetAsync(player.UserId)
end)
if ok and saved then
print(saved.Coins)
end创建文件夹后再加载数据,这样宠物就有 Pets 文件夹可以放进去。跳过不在 petInfo 中的已保存名称:从游戏中移除的宠物不应该导致玩家无法加入。
挑战
困难把玩家保存的数据还给他们。
- 在
PlayerAdded中,创建 Pets 文件夹后添加:local ok, saved = pcall(function() return saveStore:GetAsync(player.UserId) end)。 - 如果
ok and saved:将 Coins 设置为saved.Coins,并将Desert属性设置为saved.Desert。 - 对于
petInfo中保存的每只宠物,调用givePet(player, pet.Name, pet.Equipped == true)。
按“开始”,孵化宠物,再按 Stop,然后再次按“开始”:你的金币和宠物都回来了。然后按“检查”。
亲手试试
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local RunService = game:GetService("RunService")
local DataStoreService = game:GetService("DataStoreService")
local Settings = require(game.ReplicatedStorage.Settings)
local remotes = game.ReplicatedStorage.Remotes
local piles = workspace.Piles
local petParts = workspace.PetParts
local saveStore = DataStoreService:GetDataStore("Pets")
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
-- 宠物:玩家的 Pets 文件夹中的一个 StringValue,保存着宠物的名称,
-- 稀有度和力量则保存在属性中
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
-- 第 20 课:在这里添加加入游戏时加载数据的代码
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)
-- 保存:Coins、Desert 和每只宠物
local function save(player)
local pets = {}
for _, pet in player.Pets:GetChildren() do
table.insert(pets, { Name = pet.Value, Equipped = pet:GetAttribute("Equipped") == true })
end
local data = {
Coins = player.leaderstats.Coins.Value,
Desert = player:GetAttribute("Desert") == true,
Pets = pets,
}
pcall(function()
saveStore:SetAsync(player.UserId, data)
end)
end
Players.PlayerRemoving:Connect(save)
game:BindToClose(function()
for _, player in Players:GetPlayers() do
save(player)
end
end)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
Roblox 游戏:宠物模拟器中的所有课
自己练习: Roblox 在线编辑器