Menu
CoddyTech

收集硬币

本课属于 Coddy Lua 学习旅程的“Roblox 游戏脚本编写”单元。第 15 课,共 25 课。

宝藏踏板将 Coins 设为 100。金币每次应增加 1,但这会带来一个新问题。

每当每个身体部位触碰到物体时,Touched 都会触发一次,所以踏上金币的一步可能会触发好几次。每次增加 1 分,这样一个金币就会加好几分。

解决办法是使用防抖:用一个变量记住“这件事已经发生过”,让代码忽略重复触发:

local used = false
button.Touched:Connect(function(hit)
	if not used then
		used = true
		print("Pressed!")
	end
end)

当 used 为 false 时,not used 为 true,因此只有第一次触碰能通过 if not used。只有当两者都为真时,a and b 才为真:if player and not used then 要求有玩家,而且按钮尚未使用。

当循环连接许多部件时,要在循环内部创建变量,这样每个部件都有自己的变量。value += 1 是 value = value + 1 的简写。

challenge icon

挑战

中等

让每枚硬币恰好增加 1 个 Coin:现在穿过一枚硬币会增加好几个。

  1. 在 for 循环内、Connect 之前,添加 local collected = false。
  2. 将检查条件改为 if player and not collected then。
  3. 将 collected = true 设为其中的第一行。

按下 开始,然后穿过一枚硬币:Coins 恰好增加 1。然后按下 检查。

亲手试试

local Players = game:GetService("Players")
local coins = workspace.Coins

Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local coinsValue = Instance.new("IntValue")
	coinsValue.Name = "Coins"
	coinsValue.Value = 0
	coinsValue.Parent = leaderstats
end)

for _, coin in coins:GetChildren() do
	coin.Touched:Connect(function(hit)
		local player = Players:GetPlayerFromCharacter(hit.Parent)
		if player then
			player.leaderstats.Coins.Value += 1
		end
	end)
end

Roblox 游戏脚本编写中的所有课

自己练习: Lua 在线编译器