Menu
CoddyTech

画面上のコイン

Coddyの「Robloxゲーム:ペットシミュレーター」コースのレッスン 5/18。

次はクライアントです。PetClientはHUD内のLocalScriptです。HUDはScreenGuiで、プレイヤーがスポーンすると、RobloxがStarterGuiから各プレイヤーの画面にコピーします。LocalScriptはそのプレイヤー自身のデバイス上で実行され、実行対象のプレイヤーを取得できます。

local me = game:GetService("Players").LocalPlayer

サーバーはプレイヤーの参加直後にleaderstatsをプレイヤーに追加するため、クライアントはWaitForChildを使ってそれを待ちます。次に、HUDのCoinsラベルにコインを表示し、値が変わるたびに更新します。IntValueのChangedは新しい値とともに発火します。

ラベルに表示されるのは、サーバーが決定した内容だけです。LocalScriptでCoins.Valueを変更しても、このプレイヤーの画面上の表示が変わるだけで、サーバー上では何も変わりません。

challenge icon

チャレンジ

中級

PetClientで:

  1. Players、local me = Players.LocalPlayer、local hud = script.Parentを取得します。
  2. leaderstatsとその中のCoinsを待ちます。
  3. hud.Coins.TextをCoins: 5(値)に設定するshowCoins()を書き、一度呼び出して、Coins.Changedに接続します。

Playを押して、山を壊します。その後、Checkを押します。

自分で試してみよう

local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Settings = require(game.ReplicatedStorage.Settings)

local piles = workspace.Piles
local pileSpot = {} -- 各pile -> そのpileが置かれているspot

print("A Meadow pile gives " .. Settings.PileValue .. " coins")

-- すべてのプレイヤーのリーダーボードに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
end)

-- pileのクリック処理には、spawnPileの下で定義するhitPileが必要なので、名前を宣言する
-- ここで、どちらよりも前に
local hitPile

-- spot上のコインのpile:ServerStorage.CoinPileをコピーし、health
-- とvalueを属性として設定する
local function spawnPile(spot)
	local pile = ServerStorage.CoinPile:Clone()
	pile.Position = spot.Position
	pile:SetAttribute("MaxHealth", Settings.PileHealth)
	pile:SetAttribute("Health", Settings.PileHealth)
	pile:SetAttribute("Value", Settings.PileValue)
	-- クリックしてpileを叩く
	local detector = Instance.new("ClickDetector")
	detector.Parent = pile
	pileSpot[pile] = spot
	pile.Parent = piles
	detector.MouseClick:Connect(function(player)
		hitPile(player, pile)
	end)
	return pile
end

-- 叩くとpileの体力が1減る。
-- 0になるとpileが壊れ、その価値に応じたコインが支払われる
function hitPile(player, pile)
	local health = pile:GetAttribute("Health") - 1
	if health > 0 then
		pile:SetAttribute("Health", health)
		return
	end
	player.leaderstats.Coins.Value += pile:GetAttribute("Value")
	local spot = pileSpot[pile]
	pileSpot[pile] = nil
	pile:Destroy()
	-- 数秒後、同じspotに新しいpileを生成する
	task.delay(Settings.RespawnTime, spawnPile, spot)
end

-- Meadowのすべてのspotにpileを配置する
for _, spot in workspace.Zones.Meadow.Spawns:GetChildren() do
	spawnPile(spot)
end
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Robloxゲーム:ペットシミュレーターのすべてのレッスン