You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Roblox Lua开发问题:触发方块时显示全部消息而非单条随机消息

问题分析

你的代码里Touched事件会被多次触发(比如玩家的多个身体部位接触方块,或者碰撞检测的持续触发),每次触发都会创建新的BillboardGui并随机显示消息,所以看起来像是所有消息同时出现,实际上是多个Gui层叠在一起。

解决方案

添加一个状态变量控制触发逻辑的执行,确保同一时间只有一个消息显示。修改后的代码如下:

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 isActive = false -- 标记当前是否正在处理触发逻辑

local function onTouched(part)
    local humanoid = part.Parent:FindFirstChild("Humanoid")
    if humanoid and not isActive then
        isActive = true -- 开始处理时锁定状态,阻止重复触发
        block.BrickColor = BrickColor.new("Bright red")
        
        local text = Instance.new("BillboardGui")
        text.Parent = block
        text.Adornee = block
        text.Size = UDim2.new(1, 0, 1, 0)
        text.StudsOffset = Vector3.new(0, 2, 0)
        
        local label = Instance.new("TextLabel")
        label.Parent = 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()
        isActive = false -- 处理完成后重置状态
    end
end

block.Touched:Connect(onTouched)
关键改动说明
  • 添加isActive变量:防止Touched事件重复触发时创建多个Gui,确保同一时间仅显示一条消息
  • 调整实例父级设置:不再使用Instance.new的第二个参数(Roblox官方推荐显式设置Parent属性,避免潜在性能问题)
  • 增加状态判断:仅当isActive为false时才执行触发逻辑,确保一次处理流程完成前不会重复执行

内容的提问来源于stack exchange,提问作者veryNoobProgrammer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 09:57:30