Menu
CoddyTech

离开时保存

Coddy Roblox 游戏:宠物模拟器 课程的第 19 课,共 20 课。

玩家下次加入时,金币、沙漠和所有宠物都应该还在。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 中,发布体验并开启启用 Studio 对 API 服务的访问权限后,DataStore 才能正常工作。

challenge icon

挑战

困难

每位玩家离开时,保存他们的游戏进度。

  1. 获取 DataStoreService,并获取 local saveStore = DataStoreService:GetDataStore("Pets")。
  2. 编写 save(player):在 pcall 中调用 saveStore:SetAsync(player.UserId, data),保存 Coins、Desert 和 Pets,其中 Pets 是由 { Name = pet.Value, Equipped = ... } 组成的列表。
  3. 在 Players.PlayerRemoving 时调用它,并在 game:BindToClose 中为每位玩家调用它。

按下 Play,赚取金币,然后按下 Stop:离开时就会写入存档。然后点击 Check。

亲手试试

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

-- 一只宠物:玩家的 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
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 课:在这里添加 Save on Leave

Roblox 游戏:宠物模拟器中的所有课

自己练习: Roblox 在线编辑器