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

Roblox中按下GUI按钮音乐不静音但可打印音量,求故障原因

Roblox Lua 音频静音失效问题排查

用户代码

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local mutebutton = script.Parent


while true do
    wait()
    local b = game.StarterGui.MusicPlayer.Playlist:GetChildren()
    local c = math.random(1, #b)
    local d = b[c]
    d:Play()
    wait(d.TimeLength)
    
    mutebutton.MouseButton1Click:Connect(function()
        d.Volume = 0
    end)    
    
end

用户问题

我编写了上述Roblox Lua脚本,用于随机播放StarterGui中MusicPlayer.Playlist内的音频。当我将按钮点击事件中的d.Volume = 0替换为print(d.Volume)或print("testing")时,功能可正常执行;但设置音量为0以静音音乐时却无法生效,请问这是什么原因?


问题原因

  1. 操作对象错误:你修改的是StarterGui里的音频模板,而实际运行时玩家听到的是PlayerGui中的音频副本。StarterGui仅作为初始化模板,游戏启动后会复制到每个玩家的PlayerGui目录下,修改模板不会影响正在播放的实际音频实例。
  2. 事件绑定时机错误:每次循环播放音频时才绑定点击事件,不仅会造成重复绑定(点击一次触发多次回调),而且当音频播放结束后,d指向的是已播放完成的音频,此时绑定的事件操作的并非当前正在播放的音频。

解决方法

修改后的代码

local player = game.Players.LocalPlayer
local playerGui = player.PlayerGui -- 改为操作PlayerGui中的实例
local mutebutton = script.Parent
local currentAudio = nil -- 维护当前播放的音频引用

-- 提前绑定一次点击事件,避免重复绑定
mutebutton.MouseButton1Click:Connect(function()
    if currentAudio then
        currentAudio.Volume = 0
    end
end)

while true do
    wait()
    local audioList = playerGui.MusicPlayer.Playlist:GetChildren()
    local randomIndex = math.random(1, #audioList)
    currentAudio = audioList[randomIndex]
    
    currentAudio.Volume = 1 -- 播放前恢复音量,避免上次静音影响
    currentAudio:Play()
    wait(currentAudio.TimeLength)
    currentAudio = nil -- 播放结束后清空引用
end

关键调整说明

  • 替换StarterGui为PlayerGui,确保操作的是玩家正在使用的界面实例。
  • 将点击事件绑定移到循环外部,避免重复绑定问题。
  • 新增currentAudio变量维护当前播放的音频,确保点击事件能精准修改正在播放的音频音量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:01:08