Menu
CoddyTech

참가할 때 불러오기

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에 없는 이름은 건너뛰세요. 게임에서 삭제된 펫 때문에 플레이어의 접속이 실패해서는 안 됩니다.

challenge icon

챌린지

어려움

플레이어가 저장한 데이터를 돌려줍니다.

  1. PlayerAdded에서 Pets 폴더를 만든 다음: local ok, saved = pcall(function() return saveStore:GetAsync(player.UserId) end).
  2. ok and saved이면 Coins를 saved.Coins로 설정하고 Desert 속성을 saved.Desert로 설정합니다.
  3. 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)
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Roblox 게임: 펫 시뮬레이터의 모든 레슨

직접 연습해 보세요: Roblox 플레이그라운드