I am making a roblox game using lua. in it i want a player to stand on a block which will turn red and display a randomly chosen message from 10 messages. But all 10 messages are being displayed.
local block = script.Parent
local originalColor = block.BrickColor
local messages = {
"Message 1",
"Message 2",
"Message 3",
"Message 4",
"Message 5",
"Message 6",
"Message 7",
"Message 8",
"Message 9",
"Message 10"
}
local function onTouched(part)
local humanoid = part.Parent:FindFirstChild("Humanoid")
if humanoid then
block.BrickColor = BrickColor.new("Bright red")
local text = Instance.new("BillboardGui", block)
text.Adornee = block
text.Size = UDim2.new(1, 0, 1, 0)
text.StudsOffset = Vector3.new(0, 2, 0)
local label = Instance.new("TextLabel", text)
label.Size = UDim2.new(1, 0, 1, 0)
label.Text = messages[math.random(#messages)]
label.TextSize = label.TextSize + 10
label.TextColor3 = Color3.new(1, 1, 1)
label.BackgroundTransparency = 1
wait(3)
block.BrickColor = originalColor
text:Destroy()`your text`
end
end
block.Touched:Connect(onTouched)
The problem here is that as you walk over the part, the touched event can fire multiple times. To prevent this you can use something that is often called 'debounce' this prevents the event from being fired too often.
By checking if debounce is false, it prevents the event from being fired in quick succession.
local debounce = false
local function onTouched(part)
local humanoid = part.Parent:FindFirstChild("Humanoid")
if humanoid and not debounce then
block.BrickColor = BrickColor.new("Bright red")
local text = Instance.new("BillboardGui", block)
text.Adornee = block
text.Size = UDim2.new(1, 0, 1, 0)
text.StudsOffset = Vector3.new(0, 2, 0)
local label = Instance.new("TextLabel", text)
label.Size = UDim2.new(1, 0, 1, 0)
label.Text = messages[math.random(#messages)]
label.TextSize = label.TextSize + 10
label.TextColor3 = Color3.new(1, 1, 1)
label.BackgroundTransparency = 1
debounce = true
wait(3)
block.BrickColor = originalColor
text:Destroy()
debounce = false
end
end