Menu
CoddyTech

画面上のコイン

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

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

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

サーバーのScriptでは、LocalPlayerはnilです。サーバーはすべてのプレイヤーに同時に対応するためです。

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

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

challenge icon

チャレンジ

中級

プレイヤーのコインを画面に表示します。

  1. PetClient内で、local Players = game:GetService("Players")、local me = Players.LocalPlayer、local hud = script.Parentとします。
  2. local coins = me:WaitForChild("leaderstats"):WaitForChild("Coins")
  3. showCoins()を記述します:hud.Coins.Text = "Coins: " .. coins.Value。一度呼び出し、coins.Changedに接続します。

「プレイ」を押して山を壊すと、左上に Coins: 5 と表示されます。その後、「確認」を押します。

自分で試してみよう

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 上のコインの山:ServerStorage.CoinPile のコピーで、体力
-- と価値を属性として持つ
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)
	-- クリックするとダメージを与える
	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

-- 1 回攻撃すると 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 を 1 つずつ配置する
for _, spot in workspace.Zones.Meadow.Spawns:GetChildren() do
	spawnPile(spot)
end

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

自分で練習してみよう: Robloxプレイグラウンド